我正在尝试将来自我后端的HTML字符串转换为 textView ,我的 textView , but I want to set the font myself .
以下是来自我的服务器的HTML-String的示例:
Title
Extra info ..
- Some more info
- Contact
一些stackoverflow主题建议在服务器后端设置字体,但在我的情况下这是不可能的 .
我在网上搜索了如何创建 NSAtrributedString :使用 WebView 或 NSAttributedString ,我出于某些原因选择了第二个 . 我使用以下方法将我的HTML-String转换为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标签工作的解决方案?