Home > OS >  How to handle hex values in NSAttributedString color
How to handle hex values in NSAttributedString color

Time:09-28

I am trying to use NSAttributedString to get the color attribute from a sample HTML string. Here is how I am trying to create it:

func toHTMLAttributedString() -> NSAttributedString? {
    if let data = self.data(using: .unicode),
       let nsAttrString = try? NSAttributedString(data: data,
                                                  options: [.documentType: NSAttributedString.DocumentType.html],
                                                  documentAttributes: nil) {
            return nsAttrString
        }
        return nil
    }

Here is the string I am trying this with:

<p>My <b> cat </b> has <span style=\"color:#i00008B\">blue</span> eyes.</p>

However, the word "blue" is always black. I figured out that this was happening because it is a hex value. How can I convert the hex value to something NSAttributedString knows how to use.

CodePudding user response:

You need to remove letter i

"color:#00008B\

and then it's correct e.x for Red

let str = """
<p>My <b> cat </b> has <span style=\"color:#ff0000\">blue</span> eyes.</p>
"""

enter image description here

  • Related