Eugene Zhenya Gordin Eugene Zhenya Gordin - 3 months ago 15
iOS Question

How to show/hide UISearchController searchBar in UITableView?

In my app I have the following setup:


  • UIViewController

  • UITableView as a subview

  • tableView has a UISearchController and a search bar is a table header view

    _tableView.tableHeaderView = _searchController.searchBar;



What I want to achieve is:


  • when this screen appears the searchBar is not there

  • tap some button (nav controller right button for example) the search bar appears (maybe animates from top or something)

  • tap that button again the search bar hides



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!

Answer

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