iOS之文本中所有指定关键字改变颜色
2019-11-29 本文已影响0人
zwing
开发中会遇到一段文字中所有指定关键字改变颜色的需求,直接上代码:
- (NSAttributedString *)matchingWithKeyword:(NSString *)keyword inResultString:(NSString *)resultSting color:(UIColor *)color{
// 创建富文本
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithString:resultSting];
// 正则检索
NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:keyword options:NSRegularExpressionCaseInsensitive error:nil];
[regex enumerateMatchesInString:resultSting options:NSMatchingReportProgress range:NSMakeRange(0, resultSting.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
[newString addAttribute:(NSString*)NSForegroundColorAttributeName
value:color
range:result.range];
}];
return newString;
}