在日常開發(fā)中,避免不了需要跟 HTML 打交道,通常來說我們會(huì)選擇使用 WKWebView 來展示 HTML 內(nèi)容,但是如果是一些 HTML 片段,其實(shí)就沒必要使用 WKWebView 這么重的組件了。
很多人應(yīng)該還不知道,其實(shí) UILabel 和 UITextView 這些組件也是可以直接渲染 HTML 內(nèi)容的。今天就來講下這個(gè)話題。
轉(zhuǎn)換為 NSAttributedString
服務(wù)端下發(fā)的數(shù)據(jù)中可能是這樣的 HTML 格式的字符串:
"<b>This is Bold!</b>
<i>This is Italic!</I>
<u>This is underline!</u>
<s>This is strikethrough!</s>"
要在 UILabel 或 UITextView 中正確呈現(xiàn)這種格式,需要將其轉(zhuǎn)換為 NSAttributedString。NSAttributedString 已經(jīng)內(nèi)置了對(duì) HTML 轉(zhuǎn)換的支持。
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() 把字符串轉(zhuǎn)成 Data 數(shù)據(jù)
2、然后使用 Data 和 .html 的 documentType 參數(shù)初始化 NSAttributedString
3、 最后給 Label 的 attributedText 賦值
看下效果:

image.png
為了以后更方便使用,我給 String 寫了個(gè)擴(kuò)展
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
)
}
}
這樣代碼復(fù)用就更方便了:
htmlLabel.attributedText = htmlString.htmlAttributedString()