swift UILab 加載HTML字符串

在日常開發(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()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容