您需要使用 UISearchDisplayController,它会自动为您隐藏导航栏。这是代码,
-(void) createSearchBar
{
_searchBar = [[SearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_searchBar.delegate = self;
[self.view addSubview:_searchBar];
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;
searchDisplayController.searchResultsTableView.sectionHeaderHeight = 10;
searchDisplayController.searchResultsTableView.sectionFooterHeight = 0;
[searchDisplayController.searchResultsTableView setSeparatorColor:[Color whiteColor]];
}
您必须在 .h 文件中实现协议 UISearchBarDelegate、UISearchDisplayDelegate、UITableViewDelegate、UITableViewDataSource。
_searchBar 和 searchDisplayController 也是在 .h 文件中定义的变量。