iOS 实现搜索关键字高亮

 

/**正则匹配关键字高亮

keyword就是需要高亮的关键字

options:NSRegularExpressionCaseInsensitive 不区分大小写

*/

NSMutableAttributedString* newString = [[NSMutableAttributedString alloc] initWithString:model.totalstring];

NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:[NSString stringWithFormat:@"%@",keyWord] options:NSRegularExpressionCaseInsensitive error:nil];

[regex enumerateMatchesInString:model.totalstring options:NSMatchingReportProgress range:NSMakeRange(0, [model.totalstring length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
[newString addAttribute:(NSString*)NSForegroundColorAttributeName
value:(id)[UIColor redColor]
range:result.range];
} ];

posted @ 2017-11-28 09:39  代号姜姜程序员  阅读(1471)  评论(0编辑  收藏  举报