【发布时间】:2017-01-12 14:54:05
【问题描述】:
我在使用 NSMutableAttributedString 读取 HTML 字符串并增加其字体大小时遇到问题。
输入 HTML:<b>Lorem ipsum</b> dolor sit <i>amet</i></h3>consectetuer</h3> adipiscing elit
而NSMutableAttributedString转换如下:
let htmlData = input.data(using: .utf8)!
let htmlAttrs = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8.rawValue] as [String : Any]
do{
let new = try NSMutableAttributedString(data: htmlData, options: htmlAttrs, documentAttributes: nil)
let tillEnd = NSRange(location: 0, length: new.length)
let attr:UIFont = UIFont.systemFont(ofSize: 25)
//new.addAttribute(NSFontAttributeName, value: attr, range: tillEnd)
textView.attributedText = new
}
它能正确读取 HTML 标签并给出输出
.
但是如果我想增加字体大小并取消注释addAttribute,字体大小会增加但不会呈现HTML。
我可以将属性字符串同时包含字体大小和 HTML 呈现吗?
【问题讨论】:
-
这是正常行为。斜体和粗体在 UIFont 内(NSFontAttributeName 也是如此)。您需要迭代您的 NSAttributedString 的 NSFontAttributeName 这是一个好的开始:stackoverflow.com/a/41413014/1801544(马特回答,但不是创建像格鲁吉亚这样的新字体,而是使用与以前相同的字体)。
-
谢谢,马特的回答有效。
标签: swift nsmutableattributedstring