Change the color of a word or string
suggest changeObjective-C
UIColor *color = [UIColor redColor];
NSString *textToFind = @"redword";
NSAttributedString *existing = yourLabel.attributedText ?: [[NSAttributedString alloc] initWithString:yourLabel.text ?: @""];
NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:existing];
// search for word occurrence
NSRange range = [yourLabel.text rangeOfString:textToFind];
if (range.location != NSNotFound) {
[attrsString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
// set attributed text
yourLabel.attributedText = attrsString;
Swift
let color = UIColor.red
let textToFind = "redword"
let source = yourLabel.attributedText ?? NSAttributedString(string: yourLabel.text ?? "")
let attrsString = NSMutableAttributedString(attributedString: source)
// search for word occurrence
let range = (attrsString.string as NSString).range(of: textToFind)
if range.location != NSNotFound {
attrsString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
// set attributed text
yourLabel.attributedText = attrsString
Note:
The main idea is to use an NSMutableAttributedString and addAttribute:value:range: with NSForegroundColorAttributeName to change the color of a range:
NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
[attrsString addAttribute:NSForegroundColorAttributeName value:color range:range];
You could use another way to get the range, for example: NSRegularExpression.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents