iOS UIText 或 UILabel 显示 HTML 并正确选用编码

时间:2024-10-06 11:34:14

有的时候我们可能会选用 UIText 或 UILabel 来显示 HTML 代格式的文字。

NSAttributedString *html = [[NSAttributedString alloc] initWithData:[NSLocalizedString(@"comment", nil) dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }documentAttributes:nil error:nil];

用 UICode 这种编码方式很重要。它可以显示法语等语言的特殊字符。 比如 UTF-8就不能。Latin1,2 编码方式可以只能显示部分特殊字符。比如

“œ” 就显示不出来。

注意:不推荐使用 UIText 或 UILabel 还显示 HTML。尽量使用 UIWebView,但 UIWebView 缺点是反应速度慢。