我看到很多人写的Search Bar实现比较复杂,而且不一定能够满足需求,这里我介绍一款自制的轻量级Search Bar,非常简单实用
先介绍一个很好用的NSString的分类,作用是取出中文的首字母或者拼音
//拼音
-(NSString*)transformToPinyin{
NSMutableString *mutableString=[NSMutableString stringWithString:self];
CFStringTransform((CFMutableStringRef)mutableString,NULL,kCFStringTransformToLatin,false);
mutableString = (NSMutableString*)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
mutableString = [[mutableString stringByReplacingOccurrencesOfString:@" " withString:@""] mutableCopy];
return mutableString.lowercaseString;
}
//首字母
- (NSString *)transformToPinyinFirstLetter {
NSMutableString *stringM = [NSMutableString string];
NSString *temp = nil;
for(int i =0; i < [self length]; i++){
temp = [self substringWithRange:NSMakeRange(i, 1)];
NSMutableString *mutableString=[NSMutableString stringWithString:temp];
CFStringTransform((CFMutableStringRef)mutableString,NULL,kCFStringTransformToLatin,false);
mutableString = (NSMutableString*)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
mutableString = [[mutableString substringToIndex:1] mutableCopy];
[stringM appendString:(NSString *)mutableString];
}
return stringM.lowercaseString;
}
接下来就是设置UISearchController了,准备工作是一个全局的UISearchController并初始化,一个模型数组(这个应该都会有),一个用来保存搜索结果的数组
@property(nonatomic,strong)NSArray *modelArray;
@property(nonatomic,strong)NSMutableArray *tempModelArray;
@property(nonatomic,strong)UISearchController *searchController;
设置一下UISearchController的样式,读者可以根据自己的需要设置Placeholder
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
//此处记得遵守UISearchResultsUpdating协议
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = false;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.navigationItem.titleView = self.searchController.searchBar;
[self.searchController.searchBar setPlaceholder:@"输入首字母搜索"];
实现协议方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
[self.tempModelArray removeAllObjects];
NSString *key = [self.searchController.searchBar text].lowercaseString;
for ((自定义模型类型) *model in self.modelArray) {
//取出首字母
NSString *firstLetter = [model.(显示字段属性) transformToPinyinFirstLetter];
if ([firstLetter containsString:key]) {
[self.tempModelArray addObject:model];
}
}
[self.tableView reloadData];
}
如果读者不是用的UItableView或者UICollectionView,根据协议方法已拿到所需要的数据,读者可以自行刷新UI界面或者其他操作.
网友评论