1

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!

3

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to change the color of all the in your string:

func highlight(word: String, in str: String, with color: UIColor) -> NSAttributedString {
    let attributedString = NSMutableAttributedString(string: str)
    let highlightAttributes = [NSForegroundColorAttributeName: color]

    let nsstr = str as NSString
    var searchRange = NSMakeRange(0, nsstr.length)

    while true {
        let foundRange = nsstr.range(of: word, options: [], range: searchRange)
        if foundRange.location == NSNotFound {
            break
        }

        attributedString.setAttributes(highlightAttributes, range: foundRange)

        let newLocation = foundRange.location + foundRange.length
        let newLength = nsstr.length - newLocation
        searchRange = NSMakeRange(newLocation, newLength)
    }

    return attributedString
}

label2.attributedText = highlight(word: "the", in: stringData[1], with: .red)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.