definePresentationContext应该设置为YES,但是当与UISearchController结合使用时会中断导航

时间:2019-05-23 18:10:24

标签: ios swift

对于在常规UISearchController中带有UIViewController的设置(它也具有包含某些项目的表格视图),我收到以下警告The topViewController of the navigation controller containing the presented search controller must have definesPresentationContext set to YES

但是,在ViewController上设置definesPresentationContext = true会破坏我在搜索处于活动状态时在NavigationController上推送新ViewController的能力,这首先破坏了搜索的目的(我想先搜索然后如果用户点击结果,则将其推送到导航堆栈上。

在尝试推送新的ViewController之前,我已经设置了searchController.isActive = false

在推开另一种视图之前,还需要做些什么来消除UISearchController吗?

// The ViewController is presented inside a UINavigationController
class ViewController: UIViewController, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchController = UISearchController(searchResultsController: nil)
        navigationItem.searchController = searchController

        // If not set to true, triggers the following error:
        //    "The topViewController of the navigation controller containing
        //     the presented search controller must have definesPresentationContext set to YES"
        definesPresentationContext = true
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        navigationItem.searchController.isActive = false

        // If definesPresentationContext is true, triggers the following 
        // error when the search bar is/was focused at the time of selection:
        //     "pushViewController:animated: called on UINavigationController while an existing transition
        //      or presentation is occurring; the navigation stack will not be updated."
        navigationController?.pushViewController(UIViewController(), animated: true)
    }
}

1 个答案:

答案 0 :(得分:0)

事实证明,navigationItem.searchController.isActive = false将以动画方式关闭搜索栏。结果,当时过渡仍在进行中,导致“第二个”导航失败。

UIView.performWithoutAnimation中调用该块也不起作用。

因此解决方案是使用UISearchController.dismiss(animated:completion)将其关闭,即

searchController.dismiss(animated: false) {
    navigationController?.pushViewController(UIViewController(), animated: true)
}