如何show/hide UITableView 中的UISearchController searchBar?

How to show/hide UISearchController searchBar in UITableView?

在我的应用程序中,我有以下设置:

我要实现的是:

当搜索栏未显示时,table 看起来该栏从未出现过(没有空的 header 单元格或类似内容)

非常感谢任何形式的帮助!

您可以通过多种方式执行此操作,但我会执行以下操作:

  1. 更新 viewForHeaderInSection 方法以仅在名为 _showHeader 的新 class 属性 为真时显示 header:

    if(_showHeader) { // insert code for showing the header: // return HeaderCell; } else { return nil; }

  2. 当用户单击按钮以显示 header 时,设置一些变量并在 tableView 上调用 reloadData:

    _showHeader = YES; [_tableView reloadData];

这是我自己想出来的,也许不是最佳解决方案,但如果有人有更好的想法,我会很乐意接受它作为答案。

-(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];
}