ios实现搜索关键字高亮效果

2020-01-21 04:34:49王冬梅

ios,搜索关键字,高亮

一. 需求要求实现的效果

汉字支持汉字直接搜索、拼音全拼搜索、拼音简拼搜索

搜索匹配到的关键字高亮显示

搜索结果优先显示全部匹配、其次是拼音全拼匹配、拼音简拼匹配;关键字在结果字符串中位置越靠前,优先显示

支持搜索英文、汉字、电话号码及混合搜索

二. 需求分析

英文名称及电话号码的搜索直接使用完全匹配的方式即可

重难点是汉字的拼音相关的拼音全拼、简拼搜索,比如 “刘亦菲” 对应的搜索关键字有且只有以下三大类总计 25 种匹配汉字:“刘”、“亦”、“菲”、“刘亦”、“亦菲”、“刘亦菲”

简拼相关:"l"、"y"、"f"、"ly"、"yf"、"lyf"

全拼相关:"li"、"liu"、"liuy"、"liuyi"、"liuyif"、"liuyife"、"liuyifei"、"yi"、"yif"、"yife"、"yifei"、"fe"、"fei"

拼音的重难点还包括:比如搜索关键字为“xian”,既要匹配出“先”,也要匹配出“西安”

三. 代码设计

1. 整体流程

首先初始化原始的数据(包含汉语、英文、数字及随意组合),主要是将一个汉语字符串转化为汉语全拼拼音及每个拼音字母所对应汉字的位置 和 汉语简拼拼音和每个拼音字母对应汉字的位置,将初始化之后的信息缓存起来


+ (instancetype)personWithName:(NSString *)name hanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)pinyinFormat {
 WPFPerson *person = [[WPFPerson alloc] init];
 
 /** 将汉字转化为拼音的类方法
  * name : 需要转换的汉字
  * pinyinFormat : 拼音的格式化器
  * @"" : seperator 分隔符
  */
 NSString *completeSpelling = [PinyinHelper toHanyuPinyinStringWithNSString:name withHanyuPinyinOutputFormat:pinyinFormat withNSString:@""];
 
 // 首字母所组成的字符串
 NSString *initialString = @"";
 // 全拼拼音数组
 NSMutableArray *completeSpellingArray = [[NSMutableArray alloc] init];
 // 拼音首字母的位置数组
 NSMutableArray *pinyinFirstLetterLocationArray = [[NSMutableArray alloc] init];
 
 // 遍历每一个字符
 for (NSInteger x =0; x
根据 UISearchResultsUpdating 代理方法 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController 来实时获取输入的最新关键字,并遍历数据源,将匹配到的结果显示出来
// 更新搜索结果
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
 NSLog(@"%@", searchController.searchBar.text);
 
 [self.searchResultVC.resultDataSource removeAllObjects];
 
 for (WPFPerson *person in self.dataSource) {
  WPFSearchResultModel *resultModel = [WPFPinYinTools
            searchEffectiveResultWithSearchString:searchController.searchBar.text.lowercaseString
            nameString:person.name
            completeSpelling:person.completeSpelling
            initialString:person.initialString
            pinyinLocationString:person.pinyinLocationString
            initialLocationString:person.initialLocationString];
  
  if (resultModel.highlightRang.length) {
   person.highlightLoaction = resultModel.highlightRang.location;
   person.textRange = resultModel.highlightRang;
   person.matchType = resultModel.matchType;
   [self.searchResultVC.resultDataSource addObject:person];
  }
 };
 // 将匹配结果按照产品规则进行排序
 [self.searchResultVC.resultDataSource sortUsingDescriptors:[WPFPinYinTools sortingRules]];
 // 刷新tableView
 dispatch_async(dispatch_get_main_queue(), ^{
  [self.searchResultVC.tableView reloadData];
 });
}