- (NSMutableAttributedString *)setSearchResultStringColor:(NSString *)resultString isPhoneNumber:(BOOL)isPhoneNumber{
NSError *error = NULL;
NSString *initStr = resultString;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:initStr];
NSString *searchStr = isPhoneNumber ? [self dealWithPhoneNumber:self.searchString] : self.searchString;
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:UIColorFromRGB(0x59baf8) range:NSMakeRange(range.location,range.length)];
}
}
return str;
}
然后在实现类或cell中调用这个方法并设置属性:
[self.emailValueLabel setAttributedText:[self setSearchResultStringColor:item.email isPhoneNumber:NO]];