UISearchController not displaying correctly

I'm trying to add a UISearchController to a UIViewController that contains a UITableView (and an MKMapView too, but hopefully that's not the problem). I followed Ray Wenderlich's tutorial but I can't get the same result in terms of behaviour.

Here is my viewDidLoad:


override func viewDidLoad() {
    super.viewDidLoad()
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = NSLocalizedString("Search references by project, customer or city", comment: "")
    if #available(iOS 11.0, *) {
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = true
    } else {
        tableView.tableHeaderView = searchController.searchBar
    }
    definesPresentationContext = true

    self.modeSelector.layer.cornerRadius = 5.0


    if let split = splitViewController {
        let controllers = split.viewControllers
        detailViewController = (controllers[controllers.count - 1] as! UINavigationController).topViewController as? ReferenceViewController
    }
}


Note that the #available test in the middle is because I need to support iOS up to 9.1.

Now I see several problems:

  • The search bar appears right away and I can't hide it by scrolling
  • When I focus the search bar, the top of the tableview doesn't stick to the bottom of the navigation item:

The only major difference I see with Ray Wenderlich's sample project is that since I created my project with XCode 9, my storyboard doesn't use top and bottom layout guides, but safe areas. Don't know if it's relevant, but that's the only thing I see.

Any idea what's going on and how I could fix this?

Replies

Did you ever find a solution to this?

I'm experiencing the same issue with:


navigationItem.hidesSearchBarWhenScrolling = true 


It appears immediately and won't hide when scrolling.

I know this is strange, but:

self.navigationItem.hidesSearchBarWhenScrolling = true
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.isTranslucent = true

Fix this issue for me

(Your NavigationController must be trancsluent before those operation)