Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - UISearchController with separate searchResultsController

I'm trying to figure out how to use UISearchController when you want to display the results in a separate searchResultsController - every single guide, video and tutorial I've found have all used the current viewController to present the search results, and instantiate UISearchController like so:

let searchController = UISearchController(searchResultsController: nil)

but I want to dim the view and present a new tableView with the search results, in the same way done on the App Store search. So what I've done is created a new tableViewController, given it a storyboard id, and then instantiated it like so:

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 on out. I have no idea how to display the search results in the resultsController, what to put in cellForRowAtIndexPath in the resultsController and so on.

Any help is appreciated!

like image 923
dan martin Avatar asked Jul 12 '17 14:07

dan martin


1 Answers

Managed to figure it out -

1) add this line when instantiating the searchController:

searchController.searchResultsUpdater = resultsController

2) add UISearchResultsUpdating to your resultsController like so:

class resultsController: UITableViewController, UISearchResultsUpdating {

3) add this function, also in your resultsController:

func updateSearchResults(for searchController: UISearchController) {

}

From there, you can get the search text, do stuff 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 it helps someone out!

like image 57
dan martin Avatar answered Oct 28 '22 15:10

dan martin