HtmlString = <table border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td>as</td><td> </td><td> </td><td> </td></tr><tr><td>a</td><td>a</td><td>a</td><td> </td></tr><tr><td>a</td><td> </td><td> </td><td>a</td></tr></tbody></table>
我对字符串进行了扩展,将字符串 (html) 解析为 NSAttributedString。
在 swift 3 上:
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let htmlString = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
let fullRange = NSRange(location: 0, length: htmlString.length);
htmlString.enumerateAttribute(NSFontAttributeName, in: fullRange, options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: {
(attributes, range, stop) -> Void in
let newFont = UIFont.preferredFont(fontName: FontName.kHelveticaNeueLight, fontSize: FontSize.kTextView);
htmlString.addAttribute(NSFontAttributeName, value: newFont, range: range);
});
htmlString.addAttribute(NSForegroundColorAttributeName, value:Color.kGrayDark, range:fullRange)
return htmlString;
在 swift 4 上:
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let htmlString = try? NSMutableAttributedString(
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else { return nil }
let fullRange = NSRange(location: 0, length: htmlString.length);
htmlString.enumerateAttribute(NSAttributedStringKey.font, in: fullRange, options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: {
(attributes, range, stop) -> Void in
let newFont = UIFont(name: FontName.regular.value, size: FontSize.html)
htmlString.addAttribute(NSAttributedStringKey.font, value: newFont ?? UIFont.systemFont(ofSize: FontSize.html), range: range);
});
htmlString.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.html(), range:fullRange)
return htmlString;
swift 3 结果:
swift 4 结果:
我想念 Swift 4 上的边框。有什么建议吗?
最佳答案
错误是因为我对 attributedText 使用了 Label 而不是 TextView。它适用于 textView。
关于ios - HTML 解析为 TextView(Swift 4 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904356/