iOS Regex匹配关键字并修改颜色

引入第三方框架RegexKitLite

/**
 *  根据传入的文字返回一个符合规则的富文本
 *
 *  @param title 匹配的文字
 *
 *  @return 创建的富文本
 */
-(NSAttributedString *)titleLabText:(NSString *)title
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:title];
    //匹配搜索关键字,并且改变颜色
    if(self.keyWords.length >0)
    {
        [title enumerateStringsMatchedByRegex:self.keyWords usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
            [attributeString addAttribute:NSForegroundColorAttributeName value:kSearchKeyWordsColor range:*capturedRanges];
            
        }];
    }
    return attributeString;
}
posted @ 2017-05-11 13:25  qqcc1388  阅读(833)  评论(0编辑  收藏  举报