Search code examples
iosobjective-cuitableviewuisearchcontrollersearchbar

iOS 11: UISearchController has a strange space in between UITableView and UISearchBar


I have the following code to setup my UISearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Arrays init & sorting.
    self.cities = [@[@"Boston", @"New York", @"Oregon", @"Tampa", @"Los Angeles", @"Dallas", @"Miami", @"Olympia", @"Montgomery", @"Washington", @"Orlando", @"Detroit"] sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        return [obj2 localizedCaseInsensitiveCompare:obj1] == NSOrderedAscending;
    }];

    self.results = [[NSMutableArray alloc] init];

    // A table view for results.
    UITableView *searchResultsTableView = [[UITableView alloc] initWithFrame:self.tableView.frame];
    searchResultsTableView.dataSource = self;
    searchResultsTableView.delegate = self;

    // Registration of reuse identifiers.
    [searchResultsTableView registerClass:UITableViewCell.class forCellReuseIdentifier:Identifier];
    [self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:Identifier];

    // Init a search results UITableViewController and setting its UITableView.
    self.searchResultsTableViewController = [[UITableViewController alloc] init];
    self.searchResultsTableViewController.tableView = searchResultsTableView;

    // Init a UISearchController with its UITableViewController for results.
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultsTableViewController];
    self.searchController.searchResultsUpdater = self;
    self.searchController.delegate = self;

    // Make an appropriate size for UISearchBar and add it as a header view for initial UITableView.
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;

    // Enable presentation context.
    self.definesPresentationContext = YES;
}

This works well, except on iOS 11. There seems to be two issues. First is when I am searching there is a gap in between table bar and search bar.

enter image description here

The other issue is when I exit the UISearchController the first cell in tableView is slightly cut off by the search bar.

enter image description here

Is there a way to fix this issue?


Solution

  • Do autolayout properly of your tableview. Remove all constraints and do it, remember your vertical space constraint should be 0.

    Thanks.