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

来源:互联网 发布:eos utility mac安装 编辑:程序博客网 时间:2024/06/06 18:43

- (NSMutableAttributedString *)setSearchResultStringColor:(NSString *)resultString isPhoneNumber:(BOOL)isPhoneNumber{

    NSError *error = NULL;

    NSString *initStr = resultString;

    NSMutableAttributedString *str = [[NSMutableAttributedStringalloc] initWithString:initStr];

    

    NSString *searchStr = isPhoneNumber ? [selfdealWithPhoneNumber:self.searchString] :self.searchString;

    

    NSRegularExpression *expression = [NSRegularExpressionregularExpressionWithPattern:searchStroptions:NSRegularExpressionCaseInsensitiveerror:&error];

    

    NSArray *rangeArray = [expressionmatchesInString:initStr options:0range:NSMakeRange(0, initStr.length)];

    

    for (NSTextCheckingResult *resultin rangeArray) {

        NSRange range = [resultrange];

        

        if (range.location !=NSNotFound) {

            [str addAttribute:NSForegroundColorAttributeNamevalue:UIColorFromRGB(0x59baf8)range:NSMakeRange(range.location,range.length)];

        }

    }

    

    return str;

}


然后在实现类或cell中调用这个方法并设置属性:

[self.emailValueLabelsetAttributedText:[selfsetSearchResultStringColor:item.emailisPhoneNumber:NO]];


0 0