项目地址:iOS 关键词高亮显示
在做搜索时,经常用到关键字高亮。以下是我的项目用到的关键字高亮。
1 //关键字数组 关键字颜色
[lb setAttributedText:text withRegularPattern:[text regularPattern:keyArr] attributes:@{ NSForegroundColorAttributeName : [UIColor redColor]}];
2
/**
关键字 正则判断
*/
-(NSString *)regularPattern:(NSArray *)keys{
NSMutableString *pattern = [[NSMutableString alloc]initWithString:@"(?i)"];
for (NSString *key in keys) {
[pattern appendFormat:@"%@|",key];
}
return pattern;
}
3
/**
关键字高亮设置
*/
- (void)setAttributedText:(NSString *)text
withRegularExpression:(NSRegularExpression *)expression
attributes:(NSDictionary *)attributesDict
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[expression enumerateMatchesInString:text
options:0
range:NSMakeRange(0, [text length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange matchRange = [result range];
if (attributesDict) {
[attributedString addAttributes:attributesDict range:matchRange];
}
if ([result resultType] == NSTextCheckingTypeLink) {
NSURL *url = [result URL];
[attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
}
}];
[self setAttributedText:attributedString];
}