更改單詞或字串的顏色

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。