在日常开发中,避免不了需要跟 HTML
打交道,通常来说我们会选择使用 WKWebView
来展示 HTML
内容,但是如果是一些 HTML
片段,其实就没必要使用 WKWebView
这么重的组件了。
很多人应该还不知道,其实 UILabel
和 UITextView
这些组件也是可以直接渲染 HTML
内容的。今天就来讲下这个话题。
转换为 NSAttributedString
服务端下发的数据中可能是这样的 HTML
格式的字符串:
"<b>This is Bold!</b>
<i>This is Italic!</i>
<u>This is underline!</u>
<s>This is strikethrough!</s>"
要在 UILabel
或 UITextView
中正确呈现这种格式,需要将其转换为 NSAttributedString
。NSAttributedString
已经内置了对 HTML
转换的支持。
let htmlLabel = UILabel(frame: CGRect(x: 0, y: 80, width: view.bounds.width, height: 200))
let htmlString = "<b>This is Bold!</b><i>This is Italic!</i><u>This is underline!</u><s>This is strikethrough!</s>"
let data = htmlString.data(using: .utf8)!
let attributedString = try? NSAttributedString(
data: data,
options: [.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
htmlLabel.attributedText = attributedString
view.addSubview(htmlLabel)
稍微解释一下代码:
1、首先利用 htmlString.data()
把字符串转成 Data
数据
2、然后使用 Data
和 .html
的 documentType
参数初始化 NSAttributedString
3、 最后给 Label
的 attributedText
赋值
看下效果:
实现扩展
为了以后更方便使用,我给 String 写了个扩展
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: .utf8) else {
return nil
}
return try? NSAttributedString(
data: data,
options: [.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil
)
}
}
这样代码复用就更方便了:
htmlLabel.attributedText = htmlString.htmlAttributedString()
点击下方公众号卡片,关注我,每天分享一个关于 iOS 的新知识
本文同步自微信公众号 “iOS新知”,每天准时分享一个新知识,这里只是同步,想要及时学到就来关注我吧!