Search code examples
iosswiftnsattributedstring

Set color to text while rendering HTML view in UITextView swift


I am rendering a HTML view in an UITextView using swift. Here is the code.

guard let attributedString = try? NSAttributedString(data: htmlContent.data(using: String.Encoding.utf8)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)  else {
            return
        }



textView.attributedText = attributedString

Now I want to set color of the text to white. How to do it?


Solution

  • Simply use the textView's textColor property:

    // ...
    textView.attributedText = attributedString
    textView.textColor = .white
    

    You could also set the foregroundColor on the attributed string itself - therefor you have to switch to an NSMutableAttributedString though:

    // ...
    attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: attributedString.length))
    textView.attributedText = attributedString