- 目標(biāo)效果如下, 將一段字符串中數(shù)字的顏色改變成其他顏色:
思路: 通過(guò)正則表達(dá)式, 找到數(shù)字部分在字符串中的位置, 然后創(chuàng)建富文本, 修改數(shù)字部分顏色
具體的代碼如下, 正則表達(dá)式是
([0-9]\\d*\\.?\\d*)
郭膛。 (注意: 下面的代碼, 放在了自定義的NSString分類中)
/**
修改字符串中數(shù)字顏色, 并返回對(duì)應(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 = @"輪胎價(jià)格195.5元起, 訂單滿100.00元減10元, 訂單滿200元減25.50元, 訂單滿300.55元送風(fēng)炮機(jī)風(fēng)炮機(jī)風(fēng)炮機(jī)風(fēng)炮機(jī)風(fēng)炮機(jī)風(fēng)炮機(jī)風(fēng)炮機(jī)...";
label.attributedText = [title modifyDigitalColor:[UIColor orangeColor] normalColor:[UIColor blackColor]];
- 如果想要把效果圖中數(shù)字后面的元也就修改, 只需要在正則表達(dá)式最后加一個(gè)
元
字, 即:([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;
}
- 最終效果: