swift string转为html,Swift:使用自定义字体从HTML创建字符串

我正在尝试将来自我后端的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标签工作的解决方案?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值