iOS開發(fā): 設(shè)置字符串中數(shù)字的顏色

  • 目標(biāo)效果如下, 將一段字符串中數(shù)字的顏色改變成其他顏色:
目標(biāo)效果
  • 思路: 通過正則表達(dá)式, 找到數(shù)字部分在字符串中的位置, 然后創(chuàng)建富文本, 修改數(shù)字部分顏色

  • 具體的代碼如下, 正則表達(dá)式是([0-9]\\d*\\.?\\d*)。 (注意: 下面的代碼, 放在了自定義的NSString分類中)

/**
 修改字符串中數(shù)字顏色, 并返回對應(yīng)富文本
 
 @param color 數(shù)字顏色, 包括小數(shù)
 @param normalColor 默認(rèn)顏色
 @return 結(jié)果富文本
 */
- (NSMutableAttributedString *)modifyDigitalColor:(UIColor *)color normalColor:(UIColor *)normalColor;
{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"([0-9]\\d*\\.?\\d*)" options:0 error:NULL];
    
    NSArray<NSTextCheckingResult *> *ranges = [regular matchesInString:self options:0 range:NSMakeRange(0, [self length])];
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSForegroundColorAttributeName : normalColor}];
    
    for (int i = 0; i < ranges.count; i++) {
        [attStr setAttributes:@{NSForegroundColorAttributeName : color} range:ranges[i].range];
    }
    return attStr;
}
  • 具體使用:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
label.numberOfLines = 0;
label.backgroundColor = [UIColor whiteColor];
[self.view addSubview:label];

NSString *title = @"輪胎價格195.5元起, 訂單滿100.00元減10元, 訂單滿200元減25.50元, 訂單滿300.55元送風(fēng)炮機風(fēng)炮機風(fēng)炮機風(fēng)炮機風(fēng)炮機風(fēng)炮機風(fēng)炮機...";

label.attributedText = [title modifyDigitalColor:[UIColor orangeColor] normalColor:[UIColor blackColor]];
  • 如果想要把效果圖中數(shù)字后面的元也就修改, 只需要在正則表達(dá)式最后加一個字, 即: ([0-9]\\d*\\.?\\d*)元
  • 代碼如下:
- (NSMutableAttributedString *)modifyDigitalColor:(UIColor *)color normalColor:(UIColor *)normalColor;
{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"([0-9]\\d*\\.?\\d*)元" options:0 error:NULL];
    
    NSArray<NSTextCheckingResult *> *ranges = [regular matchesInString:self options:0 range:NSMakeRange(0, [self length])];
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSForegroundColorAttributeName : normalColor}];
    
    for (int i = 0; i < ranges.count; i++) {
        [attStr setAttributes:@{NSForegroundColorAttributeName : color} range:ranges[i].range];
    }
    return attStr;
}
  • 最終效果:
最終效果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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