Change the color of a word or string

suggest change


UIColor *color = [UIColor redColor];
NSString *textToFind = @"redword";

NSMutableAttributedString *attrsString =  [[NSMutableAttributedString alloc] initWithAttributedString:yourLabel.attributedText];

// 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;


let color =;
let textToFind = "redword"
let attrsString =  NSMutableAttributedString(string:yourlabel.text!);
// search for word occurrence
let range = (yourlabel.text! as NSString).range(of: textToFind)
if (range.length > 0) {
// set attributed text
yourlabel.attributedText = attrsString


The main here is to use a NSMutableAttributedString and the selector addAttribute:value:range with the attribute NSForegroundColorAttributeName to change a color of a string 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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents