我正在使用 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)
关于iphone - 在 iOS 中将 HTML 转换为 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43507264/