简体   繁体   中英

Possible to use named color from asset catalog in webview?

Is there any shortcut which would enable us to directly use a named / dynamic iOS color within a WebView?

I mean, the iOS knows all named colors - why not inject those into the webview?

This is what I tried and which failed to work:

<div style="color:systemBackground">Test</div>

I know that HTML and app assets are two different domains, but maybe someone knows an elegant shortcut.

I guess it could be a 2-step process. The 2nd step would replace web colors with dynamic / named colors:

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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM