【问题标题】:Possible to use named color from asset catalog in webview?可以在 webview 中使用资产目录中的命名颜色吗?
【发布时间】:2021-02-02 16:28:42
【问题描述】:
是否有任何快捷方式可以让我们在 WebView 中直接使用命名/动态 iOS 颜色?
我的意思是,iOS 知道所有命名的颜色 - 为什么不将它们注入到 webview 中?
这是我尝试过的,但失败了:
<div style="color:systemBackground">Test</div>
我知道 HTML 和应用资产是两个不同的领域,但也许有人知道一个优雅的捷径。
【问题讨论】:
标签:
html
ios
colors
asset-catalog
【解决方案1】:
我想这可能是一个两步的过程。第二步将用动态/命名颜色替换网页颜色:
let html = "Hello <u><b style='color:red'>World!</b></u>"
let data = html.data(using: .utf8)!
let string = try! NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
// we now replace all colors with appropriate dynamic ones
string.enumerateAttribute(.foregroundColor, in: NSRange(0..<string.length)) { value, range, stop in
if let color = value as? UIColor {
if color.cgColor.components == UIColor.red.cgColor.components {
string.addAttribute(.foregroundColor, value: UIColor.systemRed, range: range)
} else {
string.addAttribute(.foregroundColor, value: UIColor.label, range: range)
}
}
}