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!

WoShiNiBaBa
  • 257
  • 5
  • 19
  • Use NSAttributedString. – El Tomato Dec 08 '16 at 03:42
  • You can check this question out [Use multiple font colors in a single label - Swift](http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift) – hooliooo Dec 08 '16 at 03:53
  • Possible duplicate of [Changing specific text's color using NSMutableAttributedString in Swift](http://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift) – haider_kazal Dec 08 '16 at 05:29

2 Answers2

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.

jhd
  • 1,243
  • 9
  • 21
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)
Code Different
  • 90,614
  • 16
  • 144
  • 163