Search code examples
swiftios11uisearchcontroller

Navigation in UISearchController iOS11


I am trying to implement the same behavior like in WhatsApp. I go into Chats pull down, type in my Search and a new TableView is presented with the searchresults in it.

No problem up to this point. It looks like this:

 let searchController = UISearchController(searchResultsController: UITableViewController())

 searchController.searchResultsUpdater = self
 definesPresentationContext = true

 if #available(iOS 11.0, *) {
     self.navigationItem.searchController = searchController
 }

Now the hairy part: When I click on a result I want it to be shown like in a UINavigationController. Just like in WhatsApp. And when I click back I want to see my search with the results in it.

I tried all kind of stuff. Embed the searchResultsController in a UINavigationController. Playing around with definesPresentationContext, and so on. Maybe someone of you got a solution for this.

I do'nt want the searchResults to be displayed right in place for performance reasons. There has to be a solution with all results in the searchResultsController.

I am soooooooo thankful for any suggestions and solutions how to solve this.


Solution

  • FINALLY I FOUND THE ANSWER!!! The solution is: Create a subclass for your searchResultsController, when you instantiate the controller pass a reference of the UINavigationController to it. On selecting the cell you call this:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // yourController is the UIViewController to show your stuff
        if let yourController = storyboard?.instantiateViewController(withIdentifier: "yourController"){
            // navController is the reference to the navController of the controller where you performed the search
            navController?.pushViewController(yourController, animated: true)
        }
    }