iOS 搜索高亮匹配

示意图1
示意图2

1. 给NSString分类添加搜索字段范围检索的方法

  • 思路:将一个String通过searchText分割成一个数组,然后通过subString和searchText的长度和来获取需要检索的Range

  • 核心代码:

/** 遍历self中的searchText字段,通过block返回对应的range和索引
 * @param searchText    搜索(高亮)字段
 * @param block  检索到对象的回调, idx : 遍历对象的索引(从0开始),range :遍历对象所在范围。如果没有匹配到相关字段,block将不会被调用
 */
- (void)enumerateSearchText:(NSString *)searchText
                 usingBlock:(void (NS_NOESCAPE ^)(NSUInteger idx, NSRange range, BOOL *stop))block {
    
    if (!self.length || !searchText.length || ![self containsString:searchText]) return;
    
    NSUInteger __block len = searchText.length;
    NSUInteger __block loc = 0;
    NSArray <NSString *>*subStrings = [self componentsSeparatedByString:searchText];
    [subStrings enumerateObjectsUsingBlock:^(NSString *subText, NSUInteger idx, BOOL *stop) {
        
        loc += subText.length; // 当前idx对应searchText的location
        NSRange range = NSMakeRange(loc, len);
        
        if (block) block(idx, range, stop);
        
        loc += len; // 下一个subText的location
        if (idx == subStrings.count - 2) *stop = YES; // 到最后一个截止(不包括最后一个)
    }];
}

2. 给NSString分类添加高亮显示搜索字段的方法

/** 自动匹配搜索字段,将self生成富文本输出。 如果self == nil, 则返回 nil
 * @param searchText   搜索(高亮)字段
 * @param textColor      默认字体颜色
 * @param textFont       默认字体
 * @param searchTextColor       高亮文本颜色
 * @param searchTextFont         高亮文本字体。
 */
- (NSAttributedString *)attributedTextWithSearchText:(NSString *)searchText
                                           textColor:(UIColor *)textColor
                                            textFont:(UIFont *)textFont
                                     searchTextColor:(UIColor *)searchTextColor
                                      searchTextFont:(UIFont *)searchTextFont {
    if(!self)   return nil;
    
    NSDictionary *textAttbs = @{
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor
    };
    NSMutableAttributedString *attbText = [[NSMutableAttributedString alloc] initWithString:self attributes:textAttbs];

    if (!self.length || !searchText.length || ![self containsString:searchText])
        return attbText;

    NSDictionary __block *highlightAttbs = @{
           NSFontAttributeName: searchTextFont,
           NSForegroundColorAttributeName: searchTextColor
    };
    [self enumerateSearchText:searchText usingBlock:^(NSUInteger idx, NSRange range, BOOL *stop) {
        [attbText setAttributes:highlightAttbs range:range];
    }];
        
    return attbText;
}

3. 进一步对UILabel(分类)进行拓展(可以省略)

- (void)setText:(nullable NSString *)text
     searchText:(nullable NSString *)searchText
      textColor:(nonnull UIColor *)textColor
       textFont:(nonnull UIFont *)textFont
searchTextColor:(nonnull UIColor *)searchTextColor
 searchTextFont:(nonnull UIFont *)searchTextFont {

    self.attributedText = [text attributedTextWithSearchText:searchText
                                                   textColor:textColor
                                                    textFont:textFont
                                             searchTextColor:searchTextColor
                                              searchTextFont:searchTextFont];
}

4. 使用(在cell 中使用)

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.numberOfLines = 0;
    }
   
    NSString *text = self.searchResults[indexPath.row];
    [cell.textLabel setText:text
                 searchText:_searchBar.text
                  textColor:[UIColor colorWithWhite:0.03 alpha:1]
                   textFont:[UIFont systemFontOfSize:14]
            searchTextColor:[UIColor colorWithRed:239/255.0 green:75/255.0 blue:76/255.0 alpha:1]
             searchTextFont:[UIFont boldSystemFontOfSize:18]];
    return cell;
}

5. Demo传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 9,114评论 2 7
  • 在铁笼般的奇异空间中,存在着它。 它的四肢和脖颈被铁链栓着,无法挣脱。 烈日炎炎、土地龟裂,它无处可藏,只能忍受皮...
    南吕娄未阅读 1,371评论 0 0
  • 19.4.21好事第107天 1.复活节去医院给患者送复活蛋分享复活节喜乐。复活彩蛋的意义代表给他们新的生命。代表...
    伯铎_4431阅读 1,007评论 0 0
  • 故 事 退伍老兵哑叔因机缘巧合捡回弃婴阿美。本就不富裕的家庭无法负担一个突如其来的孩子,老婆芝兰离家出走,哑叔一个...
    达芙妮达芙妮阅读 5,176评论 0 1