Reputation: 267
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!
Upvotes: 1
Views: 1699
Reputation: 93151
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)
Upvotes: 2
Reputation: 1253
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.
Upvotes: 4