給UILabel局部文字添加顏色

如果是整體加顏色的話,可以直接用NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color}];

然後調用UILabel的 setAttributedText:方法就可以了。

如果是局部顏色的變化,比如搜索時,需要只讓搜索關鍵字變色,此時可以用:NSMutableAttributedString *mutableAttStr = [[NSMutableAttributedString alloc] initWithAttributedString:attStr];

然後[attStr addAttribute:NSForegroundColorAttributeName value:color range:range];

就可以讓range範圍內的文字改變成color的顏色了。range可以用rangeOfString等方法求出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章