How can I change color of some parts of NSAttributed string created after HTML Rendering

Viewed 24

I have an HTML string which I rendered using the following code

extension String {
    
    var htmlToAttributedString: NSAttributedString? {
        
        guard let data = data(using: .utf8) else { return nil }
        do {
            let style = NSMutableParagraphStyle()
            style.alignment = NSTextAlignment.center
            let str =  try NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
            str.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, str.length))
            return str
        } catch {
            return nil
        }
       
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

and my HTML String looks like this

"suix swKI mn jip ipAwr ]<br>" +
    "<span style='color:#fa8508; font-size:10px; font-weight:100;'>hy (myry) mn! (gurU dI) is`iKAw sux ky pRym nwl (prmwqmw dw nwm) jipAw kr [</span><br>"

it is a very small part of my string. What I want to do is when I render my html string I want the text having collars given by style to remain the same and the text other than that to change color according to light/dark mode.

I have tried using addAttribute method with foreground property, but it changes the color of whole text, how do I preserve the color given by style in this case while being able to change color of other text. thanks

I tried using NSAtrributed string to change foreground color of some parts of my string

1 Answers

You can create 2 range of particular strings

As I have to show tagName in different color and another string in different color inside same textview

So I created 2 range and set color range wise

let attributedString = NSMutableAttributedString.init(string: completeString)
    let range = (completeString as NSString).range(of: tagName)
    let range2 = (completeString as NSString).range(of: completeString)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: range2)
    attributedString.addAttribute(NSAttributedString.Key.font, value: Constants.AppTheme.Fonts.font(type: .FONT_REGULAR, size: 16), range: range2)
    attributedString.addAttribute(NSAttributedString.Key.font, value: Constants.AppTheme.Fonts.font(type: .FONT_REGULAR, size: 16), range: range)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(hexString: "#3FC1FC"), range: range)
Related