在cellForRow 里面
//先区分是中文还是英文
if ([_searchText isChinese]) {
NSRange range = [modelTemp.uName rangeOfString:_searchText];
if (range.location != NSNotFound) {
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:modelTemp.uName];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location,range.length)];
cell.textLabel.attributedText = str;
}
}else{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:modelTemp.uName];
for (int i=0;i<modelTemp.uName.length; i++) {
//英文下要把每一个字都截取出来转化为拼音进行比较
NSString *str1 = [modelTemp.uName substringToIndex:i+1];
NSString *str2= [str1 substringFromIndex:i];
NSString *unitsName = [EaseChineseToPinyin pinyinFromChineseString:str2];
NSString *searchStr = [EaseChineseToPinyin pinyinFromChineseString:_searchText];
if ([unitsName rangeOfString:searchStr].location != NSNotFound) {
NSRange range = [modelTemp.uName rangeOfString:str2];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location,range.length)];
cell.textLabel.attributedText = str;
}
}
}
第二:搜索的刷新方法里面- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
if (searchString.length > 0 ) {
_searchText = searchString;
[self.temporyArray removeAllObjects];
if ([searchString isChinese]) {
for (BDUnitsListModel *model in self.dataArray) {
if ([model.uName rangeOfString:searchString].location != NSNotFound) {
if (![self.temporyArray containsObject:model]) {
[self.temporyArray addObject:model];
}
}
}
}else{
for (BDUnitsListModel *model in self.dataArray) {
for (int i=0;i<model.uName.length; i++) {
NSString *str1 = [model.uName substringToIndex:i+1];
NSString *str2= [str1 substringFromIndex:i];
NSString *unitsName = [EaseChineseToPinyin pinyinFromChineseString:str2];
NSString *searchStr = [EaseChineseToPinyinpinyinFromChineseString:searchString];
if ([unitsName rangeOfString:searchStr].location != NSNotFound) {
if (![self.temporyArray containsObject:model]) {
[self.temporyArray addObject:model];
}
}
}
}
}
[self.table xsq_reloadData:NO];
}
return YES;
}