您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

讓同一段文字擁有多種字體與顏色

編輯:iOS 開發綜合

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。

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