简体   繁体   中英

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!

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:

  1. Update the viewForHeaderInSection method to only show the header when a new class property called _showHeader is true:

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

  2. When the user clicks the button to show the header, set some variable and call reloadData on the tableView:

    _showHeader = YES; [_tableView reloadData];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM