首页 > 解决方案 > 你能在 Swift 的 UILabel 中显示一个 html 标签吗?

问题描述

你能<img src=''>在 aNSAttributedString中显示一个 htmlUILabel吗?

标签: htmlswiftimage

解决方案


是的,你可以,即使 Apple 不推荐它:

不应从后台线程调用 HTML 导入器(即,选项字典包含值为 html 的 documentType)。它将尝试与主线程同步,失败并超时。从主线程调用它是有效的(但如果 HTML 包含对外部资源的引用,仍然会超时,应该不惜一切代价避免这种情况)。HTML 导入机制旨在实现诸如 markdown 之类的东西(即文本样式、颜色等),而不是用于一般的 HTML 导入。

UILabelattributedText可用于呈现 html img 标签。

这里有一个例子:

let str = "<img src='https://www.codeterritory.com/assets/screenshot_sidiusnova_04-f5422e9916fb114e73484758278c284e.jpg'>"
let data = str.data(using: String.Encoding.unicode)!

do {
    let attrStr = try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html], documentAttributes: nil)    
    let label = UILabel(frame: UIScreen.main.bounds)
    label.attributedText = attrStr
    UIApplication.shared.windows.first!.addSubview(label)

} catch let error {
    print(error)
}

推荐阅读