html - 你能在 Swift 的 UILabel 中显示一个 html 标签吗?
问题描述
你能<img src=''>
在 aNSAttributedString
中显示一个 htmlUILabel
吗?
解决方案
是的,你可以,即使 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)
}
推荐阅读
- heroku - Heroku上的应用程序和Dyno之间的区别?
- php - 如何从登录页面检查 PHP 会话
- html - 如何删除图像周围不需要的白色边框?
- c# - 为什么 FileInfo Length 与传递给 CopyFileEx 进度的 TotalFileSize 不匹配
- apache-nifi - “将响应主体放入属性”在 invokeHTTP 中不起作用
- javascript - 在 React 应用程序中导入和使用 nano-memoize?
- r - Rvest 无法找到 css 选择器指定的节点,我该如何解决?
- tcl - TK 窗口没有出现
- android - 以相同的笔划大小绘制线条会产生不同粗细的线条
- php - 为 foreach() 待办事项应用提供的参数无效