Search code examples
swiftcolorstextcolornsmutableattributedstring

Change the color of specific texts within an array of string. Swift


How do you change the color of specific texts within an array of string that's going to be passed into a label?

Let's say I have an array of string:

var stringData = ["First one", "Please change the color", "don't change me"]

And then it's passed to some labels:

Label1.text = stringData[0]
Label2.text = stringData[1]
Label3.text = stringData[2]

What's the best approach to change the color of the word "the" in stringData[1]?

Thank you in advance for your help!


Solution

  • let str = NSMutableAttributedString(string: "Please change the color")
    str.addAttributes([NSForegroundColorAttributeName: UIColor.red], range: NSMakeRange(14, 3))
    label.attributedText = str
    

    The range is the range of the specific text.