我试图将来自我的后端的HTML字符串转换为NSAttributedString
,用于我的textView
,,但我想要自己设置字体。Swift:使用自定义字体从HTML创建字符串
这里是一个HTML字符串从我的服务器来的例子:
<p><strong>Title</strong></p> <p><strong>Extra info ..</strong></p><p>- Some more info</p> <p>- Contact</p>
一些计算器主题建议设置在服务器后端的字体,但是这是不可能在我的处境。
我在网上搜索关于如何创建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标签工作的解决方案?
在获得的HTML中嵌入CSS应该是可能的,但是这会感觉“脏”。我真的不知道是否没有像Android这样的更好/更简单的方法,其中有一个原生的HTML类来完成所有的工作。我会稍微等待这个话题,如果没有其他答案给出,我会接受这个答案,因为它确实有效。 – Hapeki
@Hapeki完全同意它感觉“脏”。如果你想出一个更好的方法,我会很感兴趣。 –