David Goncalves
David Goncalves

Reputation: 81

UISearchController UITableView didSelectRowAtIndexPath not working after filter

I have a UIViewController that I open by presenting it. In it avec have just a UITableView and UISearchController that :

let searchController = UISearchController(searchResultsController: nil)

if #available(iOS 11.0, *) {
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false
    definesPresentationContext = true
}

It works well. I can filter the UITableView each time the user update the UISearchBar field.

My func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function is like that :

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    dismiss(animated: true, completion: nil)
}

The first time I select a row after filtering the UItableView (when the UISearchBar is focused) my func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) is called but the dismiss(animated: true, completion: nil) does not work. It just resignFristResponder() the UISearchBar.

Then if a select again a cell, now that the UISearchBar is no more focused the dismiss(animated: true, completion: nil) works.

So I have to select twice a cell to see my UIViewController dismissed.

What is wrong with that ?

Upvotes: 3

Views: 1311

Answers (3)

Enrique
Enrique

Reputation: 1623

You need to dismiss the UISearchViewController when it is active.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  tableView.deselectRow(at: indexPath, animated: true)
  if searchController.isActive {
     searchController.dismiss(animated: true) {
      // Go to next screen
    }
  } else {
    // Go to next screen
  }
}

Upvotes: 0

Saleh Masum
Saleh Masum

Reputation: 2187

Just Makey sure you are creating your search controller like this.

let searchController: UISearchController = { let search = UISearchController(searchResultsController: nil) search.definesPresentationContext = true search.dimsBackgroundDuringPresentation = false return search }()

Especially this line. That solved my problem in ios 12

dimsBackgroundDuringPresentation = false

Once didSelectRow method starts getting called, put this line of code to dismiss Search Controller.

searchController.dismiss(animated: true, completion: nil)

Upvotes: 1

Scriptable
Scriptable

Reputation: 19750

Try calling dismiss on the searchController first

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    searchController.dismiss(animated: false)
    dismiss(animated: true)
}

I have just tested this and it works whether the search is active or not.

Upvotes: 1

Related Questions