原理
第 1 步:找出字符串中的数字字符并记录位置(相应的NSRange)
第 2 步:使用富文本 NSMutableAttributedString 实现
UILabel 添加 Category 方法或者新建 UILabel的子类,实现下面方法
.h 文件声明
- (void)setHighlightNumberText:(NSString *)text highlightColor:(UIColor *)color;
.m 文件实现
- (void)setHighlightNumberText:(NSString *)text highlightColor:(UIColor *)color
{
if (color == nil) {
self.text = text;
return;
}
NSMutableArray *numberRangs = [NSMutableArray array];
NSUInteger startIndex = 0;
NSUInteger length = 0;
for (NSUInteger i = 0; i < text.length; i ++) {
char character = [text characterAtIndex:i];
if (character >= '0' && character <= '9') {
// 找到了数字
if (length == 0) {
startIndex = i;
length++;
} else {
length++;
}
} else {
if (length != 0) {
[numberRangs addObject:NSStringFromRange(NSMakeRange(startIndex, length))];
startIndex = 0;
length = 0;
}
}
}
if (numberRangs.count == 0) {
self.text = text;
return;
}
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[attributedString addAttribute:NSForegroundColorAttributeName value:self.textColor range:NSMakeRange(0, text.length - 1)];
for (NSString *rangeStr in numberRangs) {
NSRange range = NSRangeFromString(rangeStr);
[attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
self.attributedText = attributedString;
}
网友评论