[英]How to show/hide UISearchController searchBar in UITableView?
In my app I have the following setup: 在我的应用中,我具有以下设置:
tableView has a UISearchController and a search bar is a table header view tableView有一个UISearchController,搜索栏是一个表头视图
_tableView.tableHeaderView = _searchController.searchBar; _tableView.tableHeaderView = _searchController.searchBar;
What I want to achieve is: 我想要实现的是:
when the search bar is not showing the table looks like that bar was never there ( there is no empty header cell or anything like that) 当搜索栏未显示时,表格看起来好像从未出现过该栏(没有空的标题单元格或类似的内容)
Any kind of help is highly appreciated! 任何帮助都将受到高度赞赏!
Figured this myself, maybe not the most optimal solution, but if anyone has better idea I would happily accept is as an answer. 我自己想了这个,也许不是最理想的解决方案,但是如果有人有更好的主意,我会很乐意接受。
-(void)searchButtonDidTap:(UIButton*)aButton
{
if (!_searchController){
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
[_searchController.searchBar sizeToFit];
_tableView.tableHeaderView = _searchController.searchBar;
_searchController.delegate = self;
_searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
_searchController.active = NO;
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
_tableView.tableHeaderView = _searchController.searchBar;
_searchController.searchBar.delegate = self;
}
else
{
_searchController.active = NO;
[_searchController removeFromParentViewController];
_searchController = nil;
_tableView.tableHeaderView = nil;
}
[_tableView reloadData];
}
There are many ways you could do this but I would do something like the following: 您可以通过多种方式执行此操作,但是我会执行以下操作:
Update the viewForHeaderInSection method to only show the header when a new class property called _showHeader is true: 更新viewForHeaderInSection方法以仅在名为_showHeader的新类属性为true时显示标头:
if(_showHeader) { // insert code for showing the header: // return HeaderCell; } else { return nil; }
When the user clicks the button to show the header, set some variable and call reloadData on the tableView: 当用户单击按钮以显示标题时,设置一些变量并在tableView上调用reloadData:
_showHeader = YES; [_tableView reloadData];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.