iOS开发中,搜索结果与搜索关键字匹配的位置变色

- (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]];


你可能感兴趣的:(iOS开发)