Swift - UISearchController with separate search

I am trying to understand how to use the UISearchController when you want to display the results in a separate searchResultsController - each individual guide, video and tutorial that I found all used the current viewController to present the search results and create an instance of UISearchController as follows:

let searchController = UISearchController(searchResultsController: nil) 

but I want to put out the view and introduce a new tableView with the search results, just like in the search on the App Store. So I created a new tableViewController, given its storyboard identifier, and then created it like this:

 let storyboard = UIStoryboard(name: "Main", bundle: nil) let resultsController = storyboard.instantiateViewController(withIdentifier: "searchResults") as! UITableViewController let searchController = UISearchController(searchResultsController: resultsController ) 

which seems to work. However, I'm pretty stuck from here. I do not know how to display search results in control results, what to put in cellForRowAtIndexPath in resultsController, etc.

Any help is appreciated!

+5
source share
1 answer

I managed to find out -

1) add this line when creating the searchController instance:

 searchController.searchResultsUpdater = resultsController 

2) add UISearchResultsUpdating to your controller results as follows:

 class resultsController: UITableViewController, UISearchResultsUpdating { 

3) add this feature to your results as well. Controller:

 func updateSearchResults(for searchController: UISearchController) { } 

From there, you can get the search text, do things with it, and reload the tableView:

 func updateSearchResults(for searchController: UISearchController) { let searchText = searchController.searchBar.text! //Do Stuff with the string DispatchQueue.main.async { self.tableView.reloadData() } } 

Hope this helps someone!

+4
source

Source: https://habr.com/ru/post/1269756/


All Articles