美文网首页
swift UILab 加载HTML字符串

swift UILab 加载HTML字符串

作者: UILable攻城狮 | 来源:发表于2023-08-01 14:54 被阅读0次

在日常开发中,避免不了需要跟 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 赋值

看下效果:


image.png

为了以后更方便使用,我给 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()

相关文章

网友评论

      本文标题:swift UILab 加载HTML字符串

      本文链接:https://www.haomeiwen.com/subject/zamlpdtx.html