在 iOS 8.0 及以後的系統中,我們可以用 UISearchController 非常輕鬆地在 UITableView 上添加搜索框。而在更早的版本裡,只能採用 UISearchBar + UISearchDisplayController 的組合方式,配置繁瑣且容易出錯。
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSMutableArray *allCities; // 所有城市
@property (strong, nonatomic) NSMutableArray *filteredCities; // 根據searchController搜索的城市
在 viewDidLoad 中完成初始化:
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = false;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.backgroundColor = UIColorFromHex(0xdcdcdc);
self.tableView.tableHeaderView = self.searchController.searchBar;
使用 UISearchController 需要遵循 UISearchResultsUpdating 協議並實現其中的方法:
#pragma mark - searchController delegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
[self.filteredCities removeAllObjects];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",
self.searchController.searchBar.text];
self.filteredCities = [[self.allCities filteredArrayUsingPredicate:searchPredicate] mutableCopy];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
只要 searchBar 中的內容發生變化,這個方法就會被調用。在裡面我們用 NSPredicate 設置過濾條件——contains[c] 中的 [c] 表示忽略大小寫。
引入搜索框之後,列表的數據源也要相應變化:cell 中到底展示 allCities 還是 filteredCities?判斷依據是 UISearchController 的 active 屬性,也就是搜索框是否處於激活狀態。Table View 的多個方法都需要做這個判斷:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (!self.searchController.active) {
return self.cityKeys.count;
} else {
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (!self.searchController.active) {
NSString *key = self.cityKeys[section];
NSArray *citySection = self.cityDict[key];
return citySection.count;
} else {
return self.filteredCities.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// 根據UISearchController的active屬性來判斷cell中的內容
if (!self.searchController.active) {
NSString *key = self.cityKeys[indexPath.section];
cell.textLabel.text = [self.cityDict[key] objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = self.filteredCities[indexPath.row];
}
return cell;
}
這一點很容易被忽略:必須在 viewWillDisappear 中主動移除 UISearchController,否則切換到下一個界面時,搜索框還會短暫殘留一幀。
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (self.searchController.active) {
self.searchController.active = NO;
[self.searchController.searchBar removeFromSuperview];
}
}
整體流程可以概括為四步:聲明並初始化 UISearchController、實現 updateSearchResultsForSearchController: 做數據過濾、根據 active 狀態切換列表數據源、頁面離開時清理搜索框。相比舊方案,新寫法 API 更清晰,也不用手動管理搜索框的顯示與動畫。