UILabel顯示多種顏色的字體

有的時(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ǔ)充:
例子下載地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容