NSString:去掉<b></b>并为该段制作带有颜色的属性字符串? [英] NSString: strip out <b></b> and make an attributed string with color for that segment?

查看:45
本文介绍了NSString:去掉<b></b>并为该段制作带有颜色的属性字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串:

这是一个 <b > 简单 </b > 字符串.

This is a < b >simple < /b > string.

我需要去掉 <b >,(抱歉b和尖括号之间没有空格,因为某些原因预览没有显示出来),还把简单"这个词加粗,我的想法是:

I need to get rid of the < b >, (sorry there is no space between b and angle bracket, for some reason the preview does not show it), also make the word 'simple' to be bold, my thought was:

  1. 用空格替换尖括号和 br
  2. 使简单"段具有属性

问题是标签去掉后,我还需要知道单词的位置,我是不是先记住'simple'的位置,去掉后,location-4应该是'simple'的新位置吗?有没有更好的办法?或者甚至将 html 标签转换为属性?

The problem is once the tags are removed, I still need to know the word's location, do I first remember the location of 'simple', after removal, the location-4 should be the new location of 'simple'? Is there any better way? Or even transform html tag to attributes?

谢谢

应该是 b 而不是 br

edit: Should be b instead of br

推荐答案

iOS 7 中提供的 API 使这变得非常容易.它将(可能的)HTML 文本的 NSString 转换为 NSAttributedString.

There is API available in iOS 7 that makes this very easy. It will convert an NSString of (possible) HTML text to an NSAttributedString.

NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType };

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithData:[myHTMLString dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];

它甚至会保留任何应用的内嵌 CSS,甚至是 background-color

It will even preserve any in-line CSS applied, even background-color!

请注意,如果 HTML 文本中未指定字体和字体大小,则默认为 Times New Roman 12.您可以以这种方式指定: