UISearchBar gets cut off when using a UINavigation

2019-05-03 10:05发布

问题:

I am trying to implement a search bar within one of the tabs in my UITabBarController, the tab is a UITableViewController within a UINavigationController...I am following an Apple tutorial - I have tried a lot of different options including answers mention here

Search bar gets cut off when using UISearchController with a UITabBarController inside a UINavigationController

I have tried setting the following property using

self.definesPresentationContext = true

or

self.tabBarController?.definesPresentationContext = true

Here is my code (from UITableViewController containing UISearchBar):

/// Search controller to help us with filtering.
    var searchController: UISearchController!

/// Secondary search results table view.
    var resultsTableController: SearchResultsTableController!

override func viewDidLoad() {
    super.viewDidLoad()
    resultsTableController = SearchResultsTableController()
    resultsTableController.tableView.delegate = self

    searchController = UISearchController(searchResultsController: resultsTableController)
    searchController.searchResultsUpdater = self
    searchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = searchController.searchBar

    searchController.delegate = self
    searchController.dimsBackgroundDuringPresentation = true
    searchController.searchBar.delegate = self  // so we can monitor text changes

    self.definesPresentationContext = true
}

Here's an image of the searchbar:

And once I tap it:

回答1:

Ok, finally solved the issue. This line got it to work

self.extendedLayoutIncludesOpaqueBars = true 

My TabBar isn't translucent so I didn't think that would make a difference but I set that on my UITableviewcontroller (the controller that is displaying the UISearchController) and now search displays in the navbar correctly. I also had extend edges under top & bottom bars set to true (using Interface Builder)



回答2:

Although my search bar was working fine in iOS 9 using sizeToFit on the searchController's searchBar, as well as definesPresentationContext=true on the view controller hosting the search results view controller, something has changed in iOS 10.

The new fix that works for me is disabling Adjust Scroll View Insets on the search results view controller. I simply did this in Interface Builder. I had to leave Extend Edges enabled. Strangely enough, this makes Interface Builder show the table cells being cut off under the navigation bar, but it is not cut off at runtime.