首先创建一个PersonData类
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PersonData : NSObject
@property(nonatomic,strong)NSString *name;
@end
NS_ASSUME_NONNULL_END
在需要用到搜索的类 签署协议 定义属性
#import "ViewController.h"
#import "PersonData.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSArray *tableData;
@property(nonatomic,strong)NSMutableArray *requltData;
@property(nonatomic,strong)NSArray *tableIndexData;
@property(nonatomic,strong)NSMutableArray *requltIndexData;
@property(nonatomic,assign)BOOL searchActive;
@end
具体逻辑 以及 实现 直接上代码
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.tab];
UISearchBar *search=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
search.delegate=self;
self.navigationItem.titleView=search;
NSArray *arr = @[@"Anna Haro",@"Daniel",@"David",@"刘二",@"石小文",@"范玉",@"梁涛涛",@"杜玉真",@"张宇",@"赵四",@"刘能"];//,@"沈海鹏",@"曾志伟"
NSMutableArray *personArray = [NSMutableArray arrayWithCapacity:arr.count];
for (NSString *name in arr) {
PersonData *data = [[PersonData alloc]init];
data.name = name;
[personArray addObject:data];
}
NSArray *tempArray = [self groupingSortingWithObjects:personArray withSelector:@selector(name) isEmptyArray:YES];
self.tableData = tempArray[0];
self.tableIndexData = tempArray[1];
}
-(NSArray *)groupingSortingWithObjects:(NSArray *)objects withSelector:(SEL)selector isEmptyArray:(BOOL)empty{
//UILocalizedIndexedCollation的分组排序建立在对对象的操作之上
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得到collation索引数量(26个字母和1个#)
NSMutableArray *indexArray = [NSMutableArray arrayWithArray:collation.sectionTitles];
NSUInteger sectionNumber = [indexArray count];//sectionNumber = 27
//建立每个section数组
NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:sectionNumber];
for (int index = 0; index < sectionNumber; index++) {
NSMutableArray *subArray = [NSMutableArray array];
[sectionArray addObject:subArray];
}
for (PersonData *model in objects) {
//根绝SEL方法返回的字符串判断对象应该处于哪个分区
//将每个人按name分到某个section下
NSInteger index = [collation sectionForObject:model collationStringSelector:selector];//获取name属性的值所在的位置,比如“林”首字母是L,则就把林放在L组中
NSMutableArray *tempArray = sectionArray[index];
[tempArray addObject:model];
}
//对每个section中的数组按照name属性排序
for (NSMutableArray *arr in sectionArray) {
NSArray *sortArr = [collation sortedArrayFromArray:arr collationStringSelector:selector];
[arr removeAllObjects];
[arr addObjectsFromArray:sortArr];
}
//是不是删除空数组
if (empty) {
[sectionArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSArray *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.count == 0) {
[sectionArray removeObjectAtIndex:idx];
[indexArray removeObjectAtIndex:idx];
}
}];
}
//第一个数组为tableView的数据源 第二个数组为索引数组 A B C......
return @[sectionArray,indexArray];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if (searchText.length == 0) {
_searchActive = NO;
[self.tab reloadData];
return;
}
_searchActive = YES;
_requltData = [NSMutableArray array];
_requltIndexData = [NSMutableArray array];
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
[self.tableData enumerateObjectsUsingBlock:^(NSMutableArray *obj, NSUInteger adx, BOOL * _Nonnull stop) {
if (_requltData.count == 0 || [[_requltData lastObject] count] != 0) {
[_requltData addObject:[NSMutableArray array]];
}
[obj enumerateObjectsUsingBlock:^(PersonData *person, NSUInteger bdx, BOOL * _Nonnull stop) {
NSString *tempStr = person.name;
NSString *pinyin = [self transformToPinyin:tempStr isQuanpin:NO];
if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0) {
[_requltData.lastObject addObject:person];
if (_requltIndexData == 0 || ![_requltIndexData.lastObject isEqualToString:_tableIndexData[adx]]) {
[_requltIndexData addObject:_tableIndexData[adx]];
}
}
}];
}];
if ([_requltData.lastObject count] == 0) {
[_requltData removeLastObject];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tab reloadData];
});
});
}
-(NSString *)transformToPinyin:(NSString *)originalString isQuanpin:(BOOL)quanpin{
NSMutableString *muStr = [NSMutableString stringWithString:originalString];
//汉字转成拼音
CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformMandarinLatin, NO);
//去掉音标
CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformStripDiacritics, NO);
NSArray *pinyinArray = [muStr componentsSeparatedByString:@" "];
NSMutableString *allString = [NSMutableString new];
if (quanpin) {
int count = 0;
for (int i = 0; i < pinyinArray.count; i++)
{
for (int i = 0; i < pinyinArray.count; i++) {
if (i == count)
{
[allString appendString:@"#"];
}
[allString appendFormat:@"%@",pinyinArray[i]];
}
[allString appendString:@","];
count++;
}
}
NSMutableString *initialStr = [NSMutableString new];
for (NSString *str in pinyinArray) {
if ([str length] > 0) {
[initialStr appendString:[str substringFromIndex:1]];
}
}
[allString appendFormat:@"#%@",initialStr];
[allString appendFormat:@",#%@",originalString];
return allString;
}
-(UITableView *)tab{
if (!_tab) {
_tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
_tab.delegate=self;
_tab.dataSource=self;
}
return _tab;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _searchActive ? _requltData.count : _tableData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _searchActive ? [_requltData[section] count] : [_tableData[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *str=@"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
}
PersonData * m = _searchActive ? _requltData[indexPath.section][indexPath.row] : _tableData[indexPath.section][indexPath.row];
cell.textLabel.text = m.name;
return cell;
}
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return _searchActive ? _requltIndexData : _tableIndexData;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
return [[UILocalizedIndexedCollation currentCollation]sectionForSectionIndexTitleAtIndex:index];
}
#pragma mark - Table View Delegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel * tempLab = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, self.view.bounds.size.width, 20)];
// tempLab.textAlignment = NSTextAlignmentCenter;
tempLab.text = _searchActive ? _requltIndexData[section] : _tableIndexData[section];
tempLab.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0];
return tempLab;
}