iOS7用HTML创建NSAttributedString
iOS7发布,苹果在UIKit中的NSAttributedString
下新增了一个方法:
initWithFileURL:options:documentAttributes:error:
有了它你可以从URL获取的数据来创建一个NSAttributedString
,并使用NSDocumentTypeDocumentAttribute
属性,从HTML生成对应字符串。
我们来看看例子:
// 创建从Bundle中来自HTML文件的URL
NSURL *html = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"html"];
// 用HTML创建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc]
initWithFileURL:html
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
// 创建TextView,添加attributed str
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 320, 50)];
[textView setAttributedText:attrStr];
// 显示出来
[[self view] addSubview:textView];
主要感兴趣的代码是上面第7行(”options:@{NSDocumentTy…“),用NSDictionary填充了一组键值对(key-value),其中键(NSDocumentTypeDocumentAttribute
)指定的值将识别文档类型,在我们的例子中使用HTML。
在这个例子中,我使用的下面的HTML,储存文件名为test.html。
<div style="background-color:#F1F1F1; font-size:14px; color:#304182;
text-align:center; margin-left:10px; padding-right:10px">
<p>iOS <span style="font-size:18px; color:#E88834;">Developer</span> Tips</p>
</div>
输出:
本文译自:Create NSAttributedString from HTML in iOS 7
这翻译…很拙劣呀,还好字不多,当记单词了哈哈。
刚点进去看了下,NSDocumentTypeDocumentAttribute
属性还有其他几个取值,分别是:NSPlainTextDocumentType
、NSRTFTextDocumentType
、NSRTFDTextDocumentType
,用来展示纯文本,RTF富文本也是极为方便了。
既然能从URL读那丢个NSData当然也是可以的:– initWithData:options:documentAttributes:error:
已经迫不及待想only iOS7了…