UISearchController UITableView didSelectRowAtIndexPath过滤后不起作用

时间:2018-11-06 10:03:18

标签: ios uitableview uisearchbar uisearchcontroller dismiss

我有一个UIViewController,我会通过展示打开它。 avec中只有一个UITableViewUISearchController

let searchController = UISearchController(searchResultsController: nil)

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

效果很好。每当用户更新UITableView字段时,我都可以过滤UISearchBar

我的func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)函数是这样的:

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

我第一次过滤了UItableView之后选择了一行(当UISearchBar成为焦点时),我的func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)被调用,但是dismiss(animated: true, completion: nil)不起作用。只是resignFristResponder()UISearchBar

然后,如果再次选择一个单元格,则UISearchBar不再有效,dismiss(animated: true, completion: nil)就可以工作了。

所以我必须选择一个单元格两次才能看到我的UIViewController被撤消。

这有什么问题?

3 个答案:

答案 0 :(得分:1)

尝试先在searchController上调用dismiss

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

我刚刚对此进行了测试,无论搜索是否有效,它都可以工作。

答案 1 :(得分:0)

请确保您正在创建像这样的搜索控制器。

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

尤其是这一行。那解决了我在ios 12中的问题

dimsBackgroundDuringPresentation = false

一旦didSelectRow方法开始被调用,请将这一行代码放在关闭搜索控制器的位置。

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

答案 2 :(得分:0)

UISearchViewController有效时,您需要将其关闭。

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
  }
}