美文网首页iOS开发-搜索
tableview搜索的关键字高亮

tableview搜索的关键字高亮

作者: SunnyLeong | 来源:发表于2018-09-07 09:34 被阅读347次
//cellforrow方法中
    if (self.searchController.active) {
        self.selectForwardCell.selectForwardModel = self.searchList[indexPath.row];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.selectForwardCell.selectForwardModel.name];
        UIColor *highlightedColor = [UIColor colorWithRed:0 green:131/255.0 blue:0 alpha:1.0];
        NSArray *strArr = [self rangeOfSubString:self.searchString inString:self.selectForwardCell.selectForwardModel.name];
        for (NSValue *value in strArr) {
            NSRange range = [value rangeValue];
            [attributedString addAttribute:NSForegroundColorAttributeName value:highlightedColor range:range];
        }
        self.selectForwardCell.titleLable.attributedText = attributedString;
        
    }else{
        self.selectForwardCell.selectForwardModel = self.dataSource[indexPath.row];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.selectForwardCell.selectForwardModel.name];
        self.selectForwardCell.titleLable.attributedText = attributedString;

    }

//循环查找相似的搜索关键字
- (NSArray*)rangeOfSubString:(NSString*)subStr inString:(NSString*)string {
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString*string1 = [string stringByAppendingString:subStr];
    NSString *temp;
    for(int i =0; i < string.length; i ++) {
        temp = [string1 substringWithRange:NSMakeRange(i, subStr.length)];
        if ([temp isEqualToString:subStr]) {
            NSRange range = {i,subStr.length};
            [rangeArray addObject: [NSValue valueWithRange:range]];
        }
    }
    return rangeArray;
}

相关文章

网友评论

    本文标题:tableview搜索的关键字高亮

    本文链接:https://www.haomeiwen.com/subject/asmqgftx.html