UILabel 设置文本中的数字部分高亮显示

2020-09-29  本文已影响0人  无迹天空

原理

第 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;
}
上一篇 下一篇

猜你喜欢

热点阅读