【发布时间】:2016-07-16 06:11:15
【问题描述】:
我正在尝试将来自后端的 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-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 标签工作的解决方案?
【问题讨论】:
标签: ios swift nsattributedstring