iOS11 SearchController - SearchBar removal from navigationItem leaves broken UI

Viewed 1804

When i remove the searchController from navigationItem by setting 'nil'. Empty space is left behind where it used to be instead of collapsing.

Tried calling,

searchController.dismiss()
navigationController.navigationItem.searchController.dismiss()
navigationItem.searchController.dismiss()
searchController.isActive = false

Nothing worked.


P.S - Using simulator

2 Answers

You should layout subviews after removing search controller. The trick is which superview's subview you have to layout: since navigationItem is part of navigation stack, so you should call layoutSubviews() onto current navigationController:

navigationItem.searchController = nil
navigationController?.view.setNeedsLayout()
navigationController?.view.layoutIfNeeded()

According to Apple Documentation you shouldn't call layoutSubviews() directly.

Use this :

let search = UISearchController(searchResultsController: nil)

If you are setting the below, then remove this line

self.navigationItem.searchController = search
Related