转自:http://www.jianshu.com/p/70b4f9c0cc4e
写app的时候经常会遇到需要进行本地模糊搜索的场景,然后我想能不能直接写成标准化的,传入model数据源 然后指定搜索字段,最后传出过滤后的model数组形成标准化任何地方都适用。直接贴代码
首先写一个类扩展继承于NSObject利用拿到这个model指定key的value
- (NSMutableString *)GetPropertyValueStrArr:(NSArray *)arr{
NSMutableString *mstr = [[NSMutableString alloc]init];
for (int i = 0; i<arr.count; i++){
NSString *propertyName = arr[i];
id propertyValue = [self valueForKey:(NSString *)propertyName];
if (propertyValue){
if ([self zhongwen:propertyValue]) {
//中文转英文
propertyValue = [ChineseToPinyin pinyinFromChiniseString:propertyValue];
}else if ([self yingwen:propertyValue]) {
//英文转大写
propertyValue = [propertyValue uppercaseString];
}
[mstr appendFormat:@"%@",propertyValue];
}
}
return mstr;
}
- (BOOL)yingwen:(NSString*)str
{
//正则 a-z A-Z
NSString *passWordRegex = @"[a-zA-Z]";
//正则匹配
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
//截取第一个字符判断
BOOL a = [passWordPredicate evaluateWithObject:[str substringToIndex:1]];
return a ;
}
//判断是否为中文
- (BOOL)zhongwen:(NSString*)str{
//截取第一个字符
NSString*sub = [str substringToIndex:1];
unichar c = [sub characterAtIndex:0];
if (c >=0x4E00 && c <=0x9FFF)
return YES ;
return NO;
}
然后在写一个SearchBarView继承于UISearchBar
.h
//需要去搜索的指定字段
@property (nonatomic,strong)NSArray *searchKyeArr;
//搜索数据源
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,copy)void(^searchResult)(NSMutableArray *result);
.m
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
_searchResultArr = [NSMutableArray array];
for (int i = 0; i < _dataArr.count; i ++) {
if (searchText.length > 0) {
if ([self zhongwen:searchText]) {
searchText = [self pinyinFromChiniseString:searchText];
}else if ([self yingwen:searchText]) {
searchText = [searchText uppercaseString];
}
}
id model = _dataArr[i];
NSMutableString *searchStr = [model GetPropertyValueStrArr:_searchKyeArr];
NSRange range = [searchStr rangeOfString:searchText];
if (range.length > 0) {
if (![_searchResultArr containsObject:model]) {
[_searchResultArr addObject:model];
}
}else{
[_searchResultArr removeObject:model];
}
}
if (searchText.length > 0) {
self.searchResult(_searchResultArr);
}else{
self.searchResult(_dataArr);
}
}
完成。任何列表只要传入数据源,和指定需要搜索这个数据源里面model的字段就可也完成搜索。
Demo地址:https://github.com/ZhichaoZhan/iOS---UISearchBar