Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchController clears UISearchBar text when dismissed

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?

like image 336
ma11hew28 Avatar asked Dec 31 '16 01:12

ma11hew28


2 Answers

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.

like image 122
Bryan Luby Avatar answered Nov 18 '22 04:11

Bryan Luby


In searchBarTextDidEndEditing(_:), set searchBar.text back to what it was before.

See: UISearchBar : How to prevent Cancel Button from clearing text?

like image 1
ma11hew28 Avatar answered Nov 18 '22 03:11

ma11hew28