我想将来自我的后端的HTML字符串转换为NSAttributedString,并将其应用于我的textView,但我希望能够自己设置字体。
下面是来自服务器的HTML字符串示例:
<p><strong>Title</strong></p> <p><strong>Extra info ..</strong></p><p>- Some more info</p> <p>- Contact</p>
有些stackoverflow的主题建议在服务器后端设置字体,但在我这种情况下不可能。
我在网上搜索如何创建 NSAtrributedString
:使用 WebView
或 NSAttributedString
,出于某些原因我选择了第二个。 我使用以下方法将我的HTML字符串转换为NSAttributedString:
func setHTMLFromString() -> NSAttributedString{
let attrStr = try! NSMutableAttributedString(
data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return attrStr
}
这种方法是有效的,但它会覆盖我为textView设置的默认系统字体。因此,我尝试将字体作为属性添加:
func setHTMLFromString() -> NSAttributedString{
let attrStr = try! NSMutableAttributedString(
data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
if #available(iOS 8.2, *) {
attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0, weight: UIFontWeightThin),
NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
} else {
attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0),
NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
}
return attrStr
}
现在我想要显示的字体确实显示正确了,但是所有HTML标签都停止工作了。有人知道如何设置字体并使HTML标签继续工作吗?