我正在使用 UIWebView
的实例来处理一些文本并正确着色,它以 HTML 形式给出结果,而不是在我想要的 UIWebView
中显示它使用带有 NSAttributedString
的 Core Text
显示它。
我能够创建和绘制 NSAttributedString
,但我不确定如何将 HTML 转换并映射到属性字符串。
我知道在 Mac OS X 下 NSAttributedString
有一个 initWithHTML:
方法,但这只是 Mac 的附加功能,不适用于 iOS。
我也知道有一个与此类似的问题,但没有答案,但我会再试一次,看看是否有人创造了一种方法来做到这一点,如果有,他们是否可以分享。
最佳答案
在 iOS 7 中,UIKit 添加了 initWithData:options:documentAttributes:error:
可以使用 HTML 初始化 NSAttributedString
的方法,例如:
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
在 swift 中:
let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
options: options,
documentAttributes: nil)
https://stackoverflow.com/questions/4217820/
相关文章:
ios - 如何获取在 UIWebView 中显示的 HTML 页面的标题?
ios - 如何将我的设备 token (NSData) 转换为 NSString?
iphone - UIWebView背景设置为Clear Color,但不透明
ios - 为现有对象添加扩展名的 Swift 文件命名的最佳实践是什么?
objective-c - 我如何判断一个对象是否附加了键值观察器
objective-c - 在 Cocoa 中生成一个随机的字母数字字符串
iphone - Objective-C 的 JSON 解析器比较(JSON 框架、YAJL、Tou