1

I created a UISearchController programmatically in a UITableViewController. It works fine but the search bar isn't displaying correctly with the status bar. Here is my code and some screenshots. It also makes a funny animation when canceling the search.

- (void)viewDidLoad
{
    [super viewDidLoad];

    _resultsTableViewController = [ResultsTableViewController new];
    _searchController = [[UISearchController alloc] initWithSearchResultsController:_resultsTableViewController];
    _searchController.searchResultsUpdater = _resultsTableViewController;
    _searchController.dimsBackgroundDuringPresentation = NO;
    self.definesPresentationContext = YES;
    self.tableView.tableHeaderView = _searchController.searchBar;       
}

enter image description here

There should be more padding here with the status bar. enter image description here

When you I cancel searching I get a bad animation here that's the height of the status bar. enter image description here

Berry Blue
  • 15,330
  • 18
  • 62
  • 113
  • 1
    This video from WWDC talks about how to accommodate search bars in iOS 11. Perhaps you'll find it useful! https://developer.apple.com/videos/play/fall2017/201/ – mlecoz Dec 06 '17 at 04:45

2 Answers2

4

From your screenshots it appears you're working on iOS 11, with this version the way the UISearchController search bar is added to UI has changed. On iOS 11 is the navigation item that takes care of displaying search so UIKit has not been updated to correctly handle the search bar presented in the table header view.

On iOS ≤10 you should continue to use

self.tableView.tableHeaderView = _searchController.searchBar;

but switch to

self.navigationItem.searchController = _searchController;
self.navigationItem.hidesSearchBarWhenScrolling = YES;

on iOS 11 and later.

Marco Boschi
  • 2,321
  • 1
  • 16
  • 30
  • I have code same as question and facing same issue only in iOS11.2.5 & iPhone 6s only. With all other device it is working fine. I get this issue when I click on search, type something and click on one of the item from search result -> redirects to next screen and comes back to first screen. Any idea what needs to be done? – Ganesh Pawar Sep 09 '19 at 10:37
  • It’s better to ask this in a separate question providing all the details of what’s going wrong and your code. – Marco Boschi Sep 09 '19 at 11:40
2

Just a quick additional caveat that the searchBar might still disappear on versions < iOS 11 unless you specify that you don't want it to hide the NavBar e.g.

    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = self.mySearchController;
        self.navigationItem.hidesSearchBarWhenScrolling = YES;
    } else {
        // Fallback on earlier versions
        self.tableView.tableHeaderView = self.mySearchController.searchBar;       // show the SearchBar in TV header
        self.mySearchController.hidesNavigationBarDuringPresentation = NO;
    }