导入头文件
#import "ChineseInclude.h"
#import "PinYinForObjc.h"NSMutableArray *searchResults;//可变数组,添加搜索到的数据
设置数据源
- (NSArray *)dataArray { if (!_dataArray) { _dataArray = @[@"百度",@"六六",@"谷歌",@"苹果",@"and",@"table",@"view",@"and",@"and",@"苹果IOS",@"谷歌android",@"微软",@"微软WP",@"table",@"table",@"table",@"六六",@"六六",@"六六",@"table",@"table",@"table"]; } return _dataArray;}
监听textField
[_textField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
当输入的时候进行搜索
- (void)textFieldEditChanged:(UITextField *)mySearchBar{ searchResults = [[NSMutableArray alloc]init]; if (mySearchBar.text.length>0&&![ChineseInclude isIncludeChineseInString:mySearchBar.text]) { for (int i=0; i0) { [searchResults addObject:self.dataArray[i]]; } // NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:self.dataArray[i]];// NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];// if (titleHeadResult.length>0) {// [searchResults addObject:self.dataArray[i]];// } } else { NSRange titleResult=[self.dataArray[i] rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch]; if (titleResult.length>0) { [searchResults addObject:self.dataArray[i]]; } } } } else if (mySearchBar.text.length>0&&[ChineseInclude isIncludeChineseInString:mySearchBar.text]) { for (NSString *tempStr in self.dataArray) { NSRange titleResult=[tempStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch]; if (titleResult.length>0) { [searchResults addObject:tempStr]; } } } NSLog(@"搜索结果:%@",searchResults); //在这里刷新 // [_tableView reloadData];}
效果图:
Demo下载链接:http://pan.baidu.com/s/1bncyjZD