Search code examples
iosswiftios11uisearchcontroller

iOS11 SearchController - SearchBar removal from navigationItem leaves broken UI


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


Solution

  • 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.