J D J D - 4 months ago 15
Swift Question

How do I dismiss a UISearchController view?

Context: There's a map view with a UISearchController implemented. The search controller displays its results in a different table view controller

I found this answer which explains how to dismiss the search controller within the same view. However, my results page is a different view than its origin page. I have

let resultsPage = ResultsTableViewController()
let searchController = UISearchController(searchResultsController: resultsPage)


So now when the search controller gets results, it displays them on the table view controller. When the user selects one of the results, I want to dismiss this view and go back to the map view, passing their selection along. Should I do this with a segue, or is there a better programmable approach?

Answer

Did this same thing in my app. My map view controller has a search bar. When the user enters a search string, it presents a table view controller with a list of addresses that were found. The user can select an address which then dismisses the table view controller and drops a pin on the map for the selected address.

In the table view that displays, use didSelectRowAtIndexPath to dismiss the table view controller and use a protocol/delegate to pass the selected item back to the map view controller. Have your map view controller conform to this protocol. I did this exact setup and it works well.

protocol DropPinOnSelectedLocationDelegate {
  func dropPinOnLocation(placemark:MKPlacemark)
}

class LocationSearchTable: UITableViewController {
...

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    self.mySearchController.searchBar.endEditing(true)
    if let indexPath = tableView.indexPathForCell(cell!) {
      selectedItem = matchingItems[indexPath.row].placemark
    }
    self.dismissViewControllerAnimated(true, completion: {
      self.delegate?.dropPinOnLocation(self.selectedItem!)
    })
  }
}