Search code examples
iosswiftuitableviewstatusbar

How to fix table view's search bar overlapping with status bar


I have a UITableViewController inside a navigation controller, with a search bar. This is how I add the search bar in viewDidLoad:

let resultsController = SearchTableViewController()
resultsController.people = people
searchController = UISearchController(searchResultsController: resultsController)
let searchBar = searchController.searchBar
searchBar.placeholder = "Search a person"
searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
searchController.searchResultsUpdater = resultsController

This is the result:

enter image description here

I tried editing the table view in the storyboard to add a constraint to make it further from the top view's margins, but I can't add contraints, probably because the table view is inside a UITableViewController.


Solution

  • I think you need this code.

    In your viewDidLoad method add this code:

    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
    

    And your tableview will be something like this:

    enter image description here

    EDIT:

    You can forcely scroll table with this code:

    tableView.scrollToRowAtIndexPath( NSIndexPath(index: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)