In viewDidLoad
of my custom subclass of UITableViewController
, I've set navigationItem.titleView
to the searchBar
of a UISearchController
, which I initialized with nil
for searchResultsController
.
When I tap into the search bar, enter text, and tap on the dimmed underlying content, then the UISearchController
gets deactivated (as expected) and the search text I entered gets cleared (unexpectedly).
The search text is also cleared (also unexpectedly) when I explicitly (programmatically) set the search controller to be inactive. To get around that, I store the search text before and set it back after dismissing the search controller. Although hacky, it works.
let searchText = searchBar.text // #hack
searchController.isActive = false
searchBar.text = searchText // #hack
For when the search controller is automatically dismissed, I tried something similar using the UISearchControllerDelegate
methods, i.e., storing the search text in willDismissSearchController(_:)
and setting it back in didDismissSearchController(_:)
. But, this solution still shows the search text getting cleared and then getting set back to what it was before.
How do I seamlessly keep the search bar text as is when the search controller is dismissed automatically?
For explicitly (programmatically) dismissing the search controller, UISearchController
is a view controller, so you can just call dismiss(animated:completion:)
on it rather than setting isActive = false
and resetting the search text:
searchController.dismiss(animated: true)
The search bar text will still persist in the search bar after dismissing.
In searchBarTextDidEndEditing(_:)
, set searchBar.text
back to what it was before.
See: UISearchBar : How to prevent Cancel Button from clearing text?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With