改變字符串中數(shù)字顏色

需求如圖:


581524641414_.pic.jpg

這個(gè),大家肯定都知道啊,用 UILabel.attributedText = NSMutableAttributedString
就可以滿足需求了

因?yàn)樾枨笾?,我們只需要改?數(shù)字 的顏色,所以這里用到 NSScanner
代碼如下:

 簡(jiǎn)單來說就是: for循環(huán) + NSSCanner
 - (void)setRichNumberWithLabel:(UILabel*)label Color:(UIColor *)color {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSString *tempString = nil;
for(int i =0; i < [attributedString length]; i++) {
    tempString = [label.text substringWithRange:NSMakeRange(i, 1)];
    if ([self isInt:tempString]) {
        [attributedString setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                         color, NSForegroundColorAttributeName, nil]
                                  range:NSMakeRange(i, 1)];
    }
}
label.attributedText = attributedString;
}

// 判斷是不是數(shù)字
- (BOOL)isInt:(NSString *)string {
int value;
NSScanner *scanner = [NSScanner scannerWithString:string];
return [scanner scanInt:&value] && [scanner isAtEnd];
}

 以上例子會(huì)循環(huán)的搜索字符串中的整數(shù)值,isAtEnd會(huì)緊接上一次搜索到的字符位置繼續(xù)搜索看是否存在下一個(gè)整數(shù)值,直至掃描結(jié)束。

特此記錄。

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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