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的边界。有什么建议吗?
发布于 2018-02-27 19:05:53
错误是因为我用Label代替了TextView的attributedText。它可以很好地与textView配合使用。
发布于 2018-07-12 09:06:29
如果辅助功能字体不同于默认字体,在html中调整UILabel attributedString的大小将会很有趣。在ios 11.2上测试,您将发现它们
https://stackoverflow.com/questions/48904356
复制相似问题