Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchController persisting after segue

I have an app with a UISearchController. This element of the UI is completely set up in code like this:

searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.searchBarStyle = UISearchBarStyle.Minimal  searchController.searchBar.frame = CGRectMake(searchController.searchBar.frame.origin.x, searchController.searchBar.frame.origin.y, searchController.searchBar.frame.size.width, 44.0) 

I am then adding it to my tableView's tableHeaderView

tableView.tableHeaderView = searchController.searchBar 

Everything seems to be working fine, but when it's active and I select an item in my tableView, my app segues to another view controller with the search controller persisting in the view. I'm unsure as to how this is possible since the search controller should be a subview of the table view in another view controller. How can I prevent this from happening?

screenshot

like image 955
Kilian Avatar asked Apr 06 '15 13:04

Kilian


1 Answers

You can hide the searchController manually by setting the active property to false in prepareForSegue. Add the below code in prepareForSegue()

searchController.active = false 

Alternatively, you should add the following line in viewDidLoad() to get the default behaviour

definesPresentationContext = true 

From the documentation for definesPresentationContext

A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.

Discussion

When a view controller is presented, iOS starts with the presenting view controller and asks it if it wants to provide the presentation context. If the presenting view controller does not provide a context, then iOS asks the presenting view controller's parent view controller. iOS searches up through the view controller hierarchy until a view controller provides a presentation context. If no view controller offers to provide a context, the window's root view controller provides the presentation context.

If a view controller returns true, then it provides a presentation context. The portion of the window covered by the view controller's view determines the size of the presented view controller's view. The default value for this property is false.

Important note (from @paulvs in the comments)

Little gotcha. Set definesPresentationContext on the view controller, not the search controller, I think this is worth emphasising.

like image 50
Praveen Gowda I V Avatar answered Sep 17 '22 16:09

Praveen Gowda I V