需求很常見:一整段文字裡,只想讓某幾個字換顏色或換字型。與其每次都在版面程式碼裡拼 NSAttributedString,不如把它包成 UILabel 的分類,呼叫起來乾淨得多。
分類(Category)無法直接加成員變數,所以這裡用關聯物件(objc_setAssociatedObject)把一份可變的 NSMutableAttributedString 掛在 label 上並重複利用,避免每次呼叫都重新配置。
- (void)text:(NSString *)str color:(UIColor *)color font:(UIFont *)font {
if (!str) str = self.text;
if (!color) color = self.textColor;
if (!font) font = self.font;
[self.attributeString setAttributes:@{NSForegroundColorAttributeName : color,
NSFontAttributeName : font}
range:[self.text rangeOfString:str]];
}
- (void)changeColor {
self.attributedText = self.attributeString;
}
- (NSMutableAttributedString *)attributeString {
NSMutableAttributedString *attributeString = objc_getAssociatedObject(self, _cmd);
// 文字沒變就沿用舊的富文字,不必重建
if (attributeString && [attributeString.string isEqualToString:self.text]) {
return attributeString;
}
attributeString = [[NSMutableAttributedString alloc] initWithString:self.text];
objc_setAssociatedObject(self, _cmd, attributeString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return attributeString;
}
先指定要處理的字串與樣式,再呼叫 changeColor 讓它生效:
[label text:@"限时" color:[UIColor redColor] font:[UIFont boldSystemFontOfSize:16]]; [label changeColor];
rangeOfString: 只會命中第一個符合的字串。若同一段文字裡出現多次相同字詞而你想全部處理,要改用 rangeOfString:options:range: 搭配迴圈逐次搜尋。另外,一旦設定了 attributedText,後續再改 label.text 或 label.font 通常不會生效,這是很多人踩過的坑,記得統一走分類的方法。