UILabel 的 text 只能套一組樣式,若要在同一行裡讓某幾個字換色或換字型,就得改用 NSAttributedString。做法是自己封裝一個方法,傳入 range 與樣式即可。
[self fuwenbenLabel:contentLabel
FontNumber:[UIFont systemFontOfSize:15]
AndRange:NSMakeRange(6, 1)
AndColor:RGBACOLOR(34, 150, 253, 1)];
NSMakeRange(6, 1) 代表從索引 6 開始、長度 1 的那個字。
// 為指定範圍套用字型與顏色
-(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font
AndRange:(NSRange)range AndColor:(UIColor *)vaColor {
NSMutableAttributedString *str =
[[NSMutableAttributedString alloc] initWithString:labell.text];
[str addAttribute:NSFontAttributeName value:font range:range]; // 字型
[str addAttribute:NSForegroundColorAttributeName value:vaColor range:range]; // 顏色
labell.attributedText = str;
}
如果一次要套多組樣式,把這個方法改寫成接收陣列會更好用:傳入多組「range + 樣式」,在迴圈中逐一 addAttribute 即可。另外要注意,設定 attributedText 之後,直接改 label 的 text 或 textColor 就沒有效果了,所有樣式都得透過 attributed string 處理。若還需要底線或刪除線,再補上 NSUnderlineStyleAttributeName 與 NSStrikethroughStyleAttributeName。