iOS开发-UILabel

iOS开发: 设置字符串中数字的颜色

2018-07-26  本文已影响55人  伯wen
目标效果
/**
 修改字符串中数字颜色, 并返回对应富文本
 
 @param color 数字颜色, 包括小数
 @param normalColor 默认颜色
 @return 结果富文本
 */
- (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元送风炮机风炮机风炮机风炮机风炮机风炮机风炮机...";

label.attributedText = [title modifyDigitalColor:[UIColor orangeColor] normalColor:[UIColor blackColor]];
- (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;
}
最终效果
上一篇下一篇

猜你喜欢

热点阅读