iOS 搜索高亮匹配

示意圖1
示意圖2

1. 給NSString分類添加搜索字段范圍檢索的方法

  • 思路:將一個String通過searchText分割成一個數(shù)組,然后通過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傳送門

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • iOS開發(fā)系列--網(wǎng)絡開發(fā) 概覽 大部分應用程序都或多或少會牽扯到網(wǎng)絡開發(fā),例如說新浪微博、微信等,這些應用本身可...
    lichengjin閱讀 4,022評論 2 7
  • 在鐵籠般的奇異空間中,存在著它。 它的四肢和脖頸被鐵鏈栓著,無法掙脫。 烈日炎炎、土地龜裂,它無處可藏,只能忍受皮...
    南呂婁未閱讀 229評論 0 0
  • 19.4.21好事第107天 1.復活節(jié)去醫(yī)院給患者送復活蛋分享復活節(jié)喜樂。復活彩蛋的意義代表給他們新的生命。代表...
    伯鐸_4431閱讀 158評論 0 0
  • 故 事 退伍老兵啞叔因機緣巧合撿回棄嬰阿美。本就不富裕的家庭無法負擔一個突如其來的孩子,老婆芝蘭離家出走,啞叔一個...
    達芙妮達芙妮閱讀 1,559評論 0 1

友情鏈接更多精彩內容