搜索结果修改关键字的颜色

搜索结果修改关键字的颜色

// 获取富文本 关键字的颜色也可以自由设置
// resultString:搜索结果
// searchStr: 搜索关键字
// orgColor: 原文本字体颜色
+ (NSMutableAttributedString *)setSearchResultStringColor:(NSString *)resultString searchStr:(NSString *)searchStr orgColor:(UIColor *)orgColor {
    
    NSError *error = NULL;
    
    NSString *initStr = resultString;
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:initStr];
    
    [str addAttribute:NSForegroundColorAttributeName value:orgColor range:NSMakeRange(0, str.length)];
    
    if (searchStr.length == 0) {
        return str;
    }
    
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:searchStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *rangeArray = [expression matchesInString:initStr options:0 range:NSMakeRange(0, initStr.length)];
    for (NSTextCheckingResult *result in rangeArray) {
        
        NSRange range = [result range];
        if (range.location != NSNotFound) {
            [str addAttribute:NSForegroundColorAttributeName value:COLOR_F48000 range:NSMakeRange(range.location,range.length)];
        }
    }
    return str;
}


调用

1.button调用

[tagButton setAttributedTitle:[Utils setSearchResultStringColor:title searchStr:_searchKey orgColor:_btnTxtColor] forState:UIControlStateNormal];

2.lable调用

courseName.attributedText = [Utils setSearchResultStringColor:roomMo.name searchStr:_searchKey orgColor:COLOR_B3];

你可能感兴趣的:(搜索结果修改关键字的颜色)