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

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

2. 第三方依赖

首先筛选出一个比较全的第三方库 PinYin4Objc用于汉语转拼音,拼音的 unicode 库比较全,一些新的汉字也都能转成拼音
但是由于该库好久没有更新,获取拼音文件部分代码不适合组件化的直接开发,因此我直接合到源文件里面了
汉语转拼音的格式


// 获取格式化器
+ (HanyuPinyinOutputFormat *)getOutputFormat {
 HanyuPinyinOutputFormat *pinyinFormat = [[HanyuPinyinOutputFormat alloc] init];
 /** 设置大小写
  * CaseTypeLowercase : 小写
  * CaseTypeUppercase : 大写
  */
 [pinyinFormat setCaseType:CaseTypeLowercase];
 /** 声调格式 :如 王鹏飞
  * ToneTypeWithToneNumber : 用数字表示声调 wang2 peng2 fei1
  * ToneTypeWithoutTone : 无声调表示 wang peng fei
  * ToneTypeWithToneMark : 用字符表示声调 wáng péng fēi
  */
 [pinyinFormat setToneType:ToneTypeWithoutTone];
 /** 设置特殊拼音ü的显示格式:
  * VCharTypeWithUAndColon : 以U和一个冒号表示该拼音,例如:lu:
  * VCharTypeWithV   : 以V表示该字符,例如:lv
  * VCharTypeWithUUnicode : 以ü表示
  */
 [pinyinFormat setVCharType:VCharTypeWithV];
 return pinyinFormat;
}

3. 其他细节

排序规则


+ (NSArray *)sortingRules {
 // 按照 matchType 顺序排列,即优先展示 中文,其次是全拼匹配,最后是拼音首字母匹配
 NSSortDescriptor *desType = [NSSortDescriptor sortDescriptorWithKey:@"matchType" ascending:YES];
 // 优先显示 高亮位置索引靠前的搜索结果
 NSSortDescriptor *desLocation = [NSSortDescriptor sortDescriptorWithKey:@"highlightLoaction" ascending:YES];
 return @[desType,desLocation];
}

四. 循环方法测试及优化选择过程

在优化遍历方法的过程中,测试了几种遍历方法,这里以输入关键字“wang”为测试数据,测试真机机型为iPhone SE 10.3

常规 for 循环


/**
 2017-12-06 12:02:51.943006 HighlightedSearch[4459:1871193] w
 2017-12-06 12:02:51.943431 HighlightedSearch[4459:1871193] 开始匹配,开始时间:2017-12-06 04:02:51 +0000
 2017-12-06 12:02:51.980588 HighlightedSearch[4459:1871193] 匹配结束,结束时间:2017-12-06 04:02:51 +0000,耗时:0.0372
 2017-12-06 12:02:52.284488 HighlightedSearch[4459:1871193] wa
 2017-12-06 12:02:52.284771 HighlightedSearch[4459:1871193] 开始匹配,开始时间:2017-12-06 04:02:52 +0000
 2017-12-06 12:02:52.316536 HighlightedSearch[4459:1871193] 匹配结束,结束时间:2017-12-06 04:02:52 +0000,耗时:0.0318
 2017-12-06 12:02:52.516826 HighlightedSearch[4459:1871193] wan
 2017-12-06 12:02:52.517121 HighlightedSearch[4459:1871193] 开始匹配,开始时间:2017-12-06 04:02:52 +0000
 2017-12-06 12:02:52.545542 HighlightedSearch[4459:1871193] 匹配结束,结束时间:2017-12-06 04:02:52 +0000,耗时:0.0285
 2017-12-06 12:02:52.838220 HighlightedSearch[4459:1871193] wang
 2017-12-06 12:02:52.838602 HighlightedSearch[4459:1871193] 开始匹配,开始时间:2017-12-06 04:02:52 +0000
 2017-12-06 12:02:52.880200 HighlightedSearch[4459:1871193] 匹配结束,结束时间:2017-12-06 04:02:52 +0000,耗时:0.0417
 */
for (NSInteger i = 0; i < self.dataSource.count; i++) {