Search code examples
iosuinavigationbaruisearchbarpromptswift4

IOS: UISearchBar partly covering UINavigationBar with prompt


I am using a UITableViewController with a UISearchBar. The UITableViewController is embedded in a UINavigationController. When the table view is shown the search bar is at the top as expected (below the navigation bar). The navigation bar is showing a title and a prompt.

When I click the search bar, it is moved up and hides the title in my navigation bar. The prompt is still visible. When I do not use a prompt, the search bar is still below the navigation bar as expected after I clicked it.

I have created a very simple project to demonstrate my problem. The project has the following file for a UITableViewController:

import UIKit

class searchTVC: UITableViewController, UISearchControllerDelegate, UISearchResultsUpdating {
    fileprivate let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Title"
        navigationItem.prompt = "prompt"

        tableView.backgroundColor = UIColor.gray

        // Add search bar
        searchController.delegate = self
        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()

        tableView.tableHeaderView = searchController.searchBar

        // remove separators for empty table
        tableView.tableFooterView = UIView()
    }

    func updateSearchResults(for searchController: UISearchController) {
        // ignore
    }
}

In the storyboard there is only an empty UITableViewController that is embedded in an UINavigationController. The result is shown below.

If you comment out the line that sets the prompt the behavior is as expected.

I recently updated my code to Swift 4. I cannot recall that I saw this behavior when using Swift 3, but I am not completely sure that it was introduced with Swift 4.

Am I missing something in the code or is this a bug?


Solution

  • Set these in viewDidLoad:

    self.definesPresentationContext = true
    self.edgesForExtendedLayout = .bottom