1,初始化
- (void)addSearchBar
{
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FXScreenWidth, FXScreenHeight) style:UITableViewStyleGrouped];
self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
self.tableView.sectionIndexColor = FXRGBColor(90, 90, 90);
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:self.tableView];
AllBrandViewResultViewController *result = [[AllBrandViewResultViewController alloc] init];
result.view.frame = CGRectMake(0, 0, FXScreenWidth, FXScreenHeight);
self.searchController = [[UISearchController alloc] initWithSearchResultsController:result];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = @"搜索品牌";
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
}
2, 在请求数据出设置
if (self.searchController.searchResultsController) {
AllBrandViewResultViewController *result = (AllBrandViewResultViewController *)self.searchController.searchResultsController;
result.searchResults = self.historys;
[result.tableView reloadData];
}
3 设置代理方法 UISearchResultsUpdating
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
[self searchStoreList:searchController.searchBar.text];
}
UISearchBarDelegate
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
if ([[searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:@""]) {
return ;
}
// 取消搜索框的第一响应者
[searchBar resignFirstResponder];
}
// 点击了搜索框右边“取消”按钮,结束编辑
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
searchBar.text = @"";
searchBar.showsCancelButton = NO;
searchBar.showsSearchResultsButton = NO;
[searchBar resignFirstResponder];
}