监听文本框改变:
DJSelectCityViewController.m
/** 当searchBar内的文字发生改变时调用此方法 */ - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { UIView *cover = [self.view viewWithTag:DJCoverTag]; if (searchText.length) { // 当前输入内容不为空 if(cover.subviews.count <= 0) { cover.alpha = 1.0; self.searchResultVC.view.frame = CGRectMake(0, 0, cover.width, cover.height); [cover addSubview:self.searchResultVC.view]; } // 将当前内容传递给 DJSearchCityResultViewController 以进行搜索 [self.searchResultVC setSearchText:searchText]; } else { // 当前输入内容为空 [self.searchResultVC.view removeFromSuperview]; cover.alpha = 0.2; } }
DJSearchCityResultViewController.m
#import "DJSearchCityResultViewController.h" #import "MJExtension.h" #import "DJCity.h" @interface DJSearchCityResultViewController () /** 城市列表 */ @property (nonatomic,strong) NSArray *citiesList; /** 搜索匹配到的结果 */ @property (nonatomic,strong) NSArray *matchSearchResults; @end @implementation DJSearchCityResultViewController /** 加载城市列表 */ - (NSArray *)citiesList { if (!_citiesList) { _citiesList = [DJCity mj_objectArrayWithFilename:@"cities.plist"]; } return _citiesList; } - (void)viewDidLoad { [super viewDidLoad]; } /** 设置搜索内容 */ - (void)setSearchText:(NSString *)searchText { // 将待搜索字符串转换成小写 NSString *searchFormat = searchText.lowercaseString; // 使用谓词进行搜索 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ or pinYin contains %@ or pinYinHead contains %@",searchFormat,searchFormat,searchFormat]; self.matchSearchResults = [self.citiesList filteredArrayUsingPredicate:predicate]; // 匹配完成后刷新tableView [self.tableView reloadData]; } #pragma mark - UITableView数据源方法 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.matchSearchResults.count; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [NSString stringWithFormat:@"搜索到%ld条结果",self.matchSearchResults.count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"matchResult"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } DJCity *city = self.matchSearchResults[indexPath.row]; cell.textLabel.text = city.name; return cell; } @end
最终结果:
原文:http://www.cnblogs.com/yongdaimi/p/6279638.html