您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用 Category 幫 UILabel 加上局部換色與換字型

編輯:iOS 技巧大全

需求很常見:一整段文字裡,只想讓某幾個字換顏色或換字型。與其每次都在版面程式碼裡拼 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 通常不會生效,這是很多人踩過的坑,記得統一走分類的方法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved