iOS UILabel/UIButton文字設定多個顏色

weixin_33860722發表於2016-11-17

UILabel和UIButton原理是一樣的,都是藉助富文字,以UILabel為例

    //假如我們的需求是將“註冊”兩個字設定為紅色,“同意”設定為綠色
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"點選註冊按鈕,即表示您已同意隱私條款和服務協議"];    
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"註冊"].location, [[noteStr string] rangeOfString:@"註冊"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];

    NSRange greenRange = NSMakeRange([[noteStr string] rangeOfString:@"同意"].location, [[noteStr string] rangeOfString:@"同意"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:greenRange];
    [noteLabel setAttributedText:noteStr];
    [noteLabel sizeToFit];

相關文章