天天看點

NSAttributedString——為Label設定富文本

為了在同一個Label中顯示兩種顔色的字元,如下圖(淺灰和黑色):

NSAttributedString——為Label設定富文本

這裡用到了

NSMutableAttributedString

,它可以建立自定義屬性的富文本。和它同類的還有

NSAttributedString

要實作上面一個Label中含兩種顔色字元的效果,将漢字顔色設定成淺灰色,用了下面簡單的代碼實作:

_followerLabel.text = @"關注 11";
    NSRange followerRange = [_followerLabel.text rangeOfString:@"關注"];
    NSMutableAttributedString *followerText = [[NSMutableAttributedString alloc] initWithString:_followerLabel.text];
    [followerText beginEditing];
    [followerText setAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:/ green:/ blue:/ alpha:]} range:followerRange];
    [followerText endEditing];
    _followerLabel.attributedText = followerText;