I tested the following in iOS 9 with UISearchController.
By default, whenever there is no text in the UISearchBar, the table shown will be your original table view (referred to as originalTableView from here on out). This may or may not have a black see-through layer depending on the value of dimsBackgroundDuringPresentation
.
Once the user enters any text into the UISearchBar, the contents of the new table view will be shown (I will refer to this as the searchTableView).
Note that in both of these solutions, I'm implementing the UISearchController in a manner similar to how Apple does so in this example; namely, there are two separate UITableViewController's in charge of showing the data.
Solution 1: Complicated implementation, smoother animation
For a smoother animation:
- Implement the UISearchControllerDelegate's willPresentSearchController and willDismissSearchController methods.
- In willPresent, update your originalTableView's data to get ready to display whatever zero text data you want, then call
reloadData()
.
- In willDismiss, revert the process to show the original contents and call
reloadData()
.
Example:
// here tableView refers to originalTableView
extension ViewController: UISearchControllerDelegate {
func willPresentSearchController(searchController: UISearchController) {
data = ["A", "B", "C"]
tableView.reloadData()
}
func willDismissSearchController(searchController: UISearchController) {
data = ["a", "b", "c"]
tableView.reloadData()
}
}
In this fictional example, the data is displayed as a,b,c
when the user is not focused on the UISearchBar, but is displayed as A,B,C
once the user taps on the UISearchBar.
Solution 2: Quick to implement, choppy animation
Instead of implementing the logic for the search controller in both originalTableView and searchTableView, you can use this solution to simply show the searchTableView even though it is hidden by default.
Most likely, you are already implementing the UISearchResultsUpdating protocol. By simply calling tableView.hidden = false
in that method, you should get the behavior you are after; albeit with a less than stellar animation.
// here tableView refers to searchTableView
extension SearchViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
tableView.hidden = false
filterData(text: searchController.searchBar.text!)
tableView.reloadData()
}
}