有的時(shí)候我們想一個(gè)label的text中出現(xiàn)不同的顏色,而且label出現(xiàn)的地方也很多,所以就自己寫(xiě)了個(gè)復(fù)用的UILabel的擴(kuò)展。
以下是我自己寫(xiě)的:
<pre>
@implementation UILabel(MoreColorsText)
-(void)setAttributeLabelWithtextColorPairs:(NSArray*)colorTextPairs
{
//獲取Label的帶屬性字符串
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
NSString *text = self.text;
NSRange oriRange = NSMakeRange(0, 0), changedRange = NSMakeRange(0, 0);
for (NSDictionary *textColorDic in colorTextPairs) {
//計(jì)算要修改的textRange
NSRange textRange = [text rangeOfString:textColorDic.allKeys.firstObject];
NSUInteger location = (oriRange.location + oriRange.length) + textRange.location;
changedRange = NSMakeRange(location, textRange.length);
//修改指定范圍的textColor
UIColor *curColor = nil;
if ([textColorDic.allValues.firstObject isKindOfClass:[UIColor class]]) {
curColor = textColorDic.allValues.firstObject;
}else{
curColor = [UIColor colorWithHexString:textColorDic.allValues.firstObject];
}
[attrStr addAttribute:NSForegroundColorAttributeName value:curColor range:changedRange];
//將修改的range改為舊的Range
oriRange = changedRange;
//從匹配字符串的結(jié)尾開(kāi)始截取剩下的字符串
if (textRange.location != NSNotFound &&
self.text.length > (textRange.location + textRange.length)) {
text = [text substringFromIndex:textRange.location + textRange.length];
}
}
//將修改好的AttributedString賦值給Label
self.attributedText = attrStr;
}
@end
</pre>
使用方法:
<pre>
//label的默認(rèn)text=@"123456789"
[self.label setAttributeLabelWithtextColorPairs:@[@{@"2":@"FF7200"},
@{@"7":[UIColor redColor]}]];
</pre>

屏幕快照 2015-09-20 下午12.54.27.png
以上代碼肯定會(huì)有不完善的地方歡迎大家完善和補(bǔ)充:
例子下載地址