Search code examples
htmliosswiftnsattributedstring

Change links colors and underline color of html converted to AttributedString


I would like to color the links and give special color to the underline of the links in my text that received from html.

This is what I have at the moment:

...

public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {

        if let htmlData = text.data(using: .utf8) {

            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]

            let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)

            let attributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.foregroundColor: UIColor.red]
            attributedString?.addAttributes(attributes, range: NSRange.init(location: 0, length: attributedString?.length ?? 0))
            return attributedString
        }

        return nil
    }
....

This is what I get: enter image description here

What I am looking for is regular color for the text and red for the links and green for the underline of the links


Solution

  • If you are using a UITextView, it would be enough to set the tintColor to UIColor.red and remove the following:

    let attributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.foregroundColor: UIColor.red]
    attributedString?.addAttributes(attributes, range: NSRange.init(location: 0, length: attributedString?.length ?? 0))
    

    so it would look like this:

    public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {
        if let htmlData = text.data(using: .utf8) {
            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]
            let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)
            return attributedString
        }
        return nil
    }
    
    //
    textView.tintColor = .red
    textView.attributedText = htmlStyleAttributeText(text: "random text <a href='http://www.google.com'>http://www.google.com </a> more random text")
    

    Output: enter image description here