改变字符串中数字颜色

需求如图:


改变字符串中数字颜色_第1张图片
581524641414_.pic.jpg

这个,大家肯定都知道啊,用 UILabel.attributedText = NSMutableAttributedString
就可以满足需求了

因为需求中,我们只需要改变 数字 的颜色,所以这里用到 NSScanner
代码如下:

 简单来说就是: for循环 + 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;
}

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

 以上例子会循环的搜索字符串中的整数值,isAtEnd会紧接上一次搜索到的字符位置继续搜索看是否存在下一个整数值,直至扫描结束。

特此记录。

你可能感兴趣的:(改变字符串中数字颜色)