我使用以下代码将HTML转换为NSAttributedString:
let data = Data(someHtmlString.utf8)
if let attributedString = try? NSAttributedString(data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) {
myTextView.attributedText = attributedString
}
此代码工作正常,但我想增大字体大小。我找到了一种解决方法-创建新的NSMutableAttributedString并添加字体属性:
let font = UIFont.systemFont(ofSize: 18)
let scaledString = NSMutableAttributedString(attributedString: originalAttributedString)
let range = NSRange(location: 0, length: scaledString.length)
let attributes: [String: AnyObject] = [NSFontAttributeName: font]
scaledString.addAttributes(attr, range: range)
不幸的是,这只会使字体变大,但是我失去了所有的斜体和粗体标记。如何扩大文本但保留其标记?