在搜索控制器激活时选择表行时应用程序崩溃

时间:2017-10-15 20:03:27

标签: swift tableview segue uisearchcontroller didselectrowatindexpath

当我的搜索控制器处于活动状态时,每当我选择一个表行时,我的应用程序似乎都会崩溃

注意事项:

  • 我的搜索控制器已嵌入到我的表格标题中
  • 我目前有一个修复,但是,当选择表格行时,它需要我的搜索控制器被解雇。这会导致糟糕的UI体验。我不想要解雇我的搜索控制器

以下是我的一些代码:

class ViewProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UISearchBarDelegate, UISearchResultsUpdating {

let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.sizeToFit()
    searchController.searchBar.searchBarStyle = .minimal
    searchController.searchBar.placeholder = "Search City"
    searchController.searchBar.showsCancelButton = true
    searchController.searchBar.delegate = self
    searchController.searchBar.backgroundColor = UIColor.white

    self.myTable.tableHeaderView = searchController.searchBar

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    if searchController.isActive {
        navigationController?.popViewController(animated: true)
        dismiss(animated: true, completion: nil)
    } else {

    }
    let mViewController = MController()
    let navController = UINavigationController(rootViewController: mViewController)
    present(navController,animated: true, completion: nil)
}

}

1 个答案:

答案 0 :(得分:0)

不要在细胞选择上弹出视图控制器。无需检查searchController是否处于活动状态。

示例:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // Get rid of searchController
    searchController.searchBar.endEditing(true)
    searchController.isActive = false
    searchController.dismiss(animated: true) { /* */ }

    // Deselect row
    tableView.deselectRow(at: indexPath, animated: true)

    // Present your VC here

}