【发布时间】:2014-10-13 15:14:52
【问题描述】:
我使用了UITextView,其中显示了NSAttributedString。我从服务器得到 HTML 字符串。我使用以下代码将 HTML 转换为 NSAttributedString。
NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithData:[strHTML dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
为了应用字体,我尝试了以下 2 个代码。
- 应用属性
- 自定义字符串
要应用属性,我使用下面的代码。
[attrib addAttribute:NSFontAttributeName
value:myFont
range:NSMakeRange(0, attrib.length)];
对于自定义字符串,我首先在NSString 下创建,然后在NSAttributedString 中隐藏
NSString *strHTML = [NSString stringWithFormat:@"<span style=\"font-family: myFont; font-size: 12\">%@</span>",@"my string"];
使用这两个代码字体更改成功。但 Bold 和 Italic 未应用,仅 Underline 在 NSAttributedString 中应用。
我参考下面的链接。
- iOS 7 using an HTML string as an NSAttributedString AND setting the font?
- ios7 font size change when create nsattributedstring from html
- How to add CSS of an html to NSAttributedString?
对于链接 3,我应该从服务器端应用字体和标签,然后检索 HTML 字符串吗?
任何帮助都会得到帮助!!!
【问题讨论】:
-
如果我没记错的话,问题在于
NSFontAttributeName内部的粗体和斜体效果。没有 NSItalicAttributeName 或 NSBoldAttributeName。因此,一种方法是枚举属性并以此启发您:stackoverflow.com/questions/23153156/… -
@Larme 是的,我尝试了自己并做了同样的事情。:)。谢谢。
标签: html ios ios7 nsattributedstring