简体   繁体   中英

Issue with UISearchController in UITableView on iOS 11

iOS 11 I'm having a UITableViewController with a UISearchController on the table's headerview using the following code :

if(searchController == nil)
{
    searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    searchController.dimsBackgroundDuringPresentation = false;
    searchController.searchResultsUpdater = self;
    searchController.searchBar.delegate = self;
    self.definesPresentationContext = NO;
    searchController.delegate = self;
}
self.tableView.tableHeaderView = searchController.searchBar;

[self.tableView setContentOffset:CGPointMake(0,searchController.searchBar.bounds.size.height) animated:YES];

When I run the app, the behavior I want is perfectly working for the tableview with rows more than the height of the device screen but on the case of tableview having only a few number of rows, the search bar is dropping a little bit down from the navigation bar.

When there are few cells on the tableview, the search bar drops down as in this picture

When there are more cells on the tableview, the search bar doesn't drop down

On iOS 11 the behaviour of UISearchController with tableView header has changed, now it a part of the navigationItem and you dont need the tableView. So you must check if iOS >= 11 and do the following

if (@available(iOS 11.0, *)) {
    self.navigationItem.searchController = searchController;
// ToDo : dont forget to hide the tableView 
// ...       
} else {
    self.tableView.tableHeaderView = searchController.searchBar;
    [self.tableView setContentOffset:CGPointMake(0,searchController.searchBar.bounds.size.height) animated:YES];
}

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