更改单词或字符串的颜色

Objective-C

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 = UIColor.red;
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) {
     attrsString.addAttribute(NSForegroundColorAttributeName,value:color,range:range)
}
        
// set attributed text
yourlabel.attributedText = attrsString

注意

这里的主要是使用 NSMutableAttributedString 和选择器 addAttribute:value:range 与属性 NSForegroundColorAttributeName 来改变字符串范围的颜色:

NSMutableAttributedString *attrsString =  [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
[attrsString addAttribute:NSForegroundColorAttributeName value:color range:range];

你可以使用另一种方式来获取范围,例如:NSRegularExpression。