產品上常會要求「這句話裡的某幾個字要換顏色、換字級」,例如把促銷文案中的價格標紅。這種需求用 NSAttributedString 就能漂亮解決,關鍵在於掌握要套用樣式的 NSRange。
只要給文字、字體、範圍與顏色四個參數,就能針對指定區間套用樣式:
[self fuwenbenLabel:contentLabel
FontNumber:[UIFont systemFontOfSize:15]
AndRange:NSMakeRange(6, 1)
AndColor:RGBACOLOR(34, 150, 253, 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;
}
第一,NSMakeRange 的 location 是從 0 開始算,且單位是「字元」而非位元組,若文字中混有 emoji 或組合字元,建議改用 rangeOfString: 動態取得範圍,避免寫死數字造成位移。
第二,若同一段文字需要套用多組樣式,重複呼叫上述方法會有問題——因為第二次是拿 labell.text 重新建立字串,前一次設定的樣式會被洗掉。正確做法是保留同一個 NSMutableAttributedString 實例,連續呼叫多次 addAttribute:value:range:,最後再一次指派給 attributedText。