popViewControllerAnimated:在现有的过渡或演示发生时调用 UINavigationController

popViewControllerAnimated: called on UINavigationController while an existing transition or presentation is occurring

我有一个表格视图,只要有人按下一个单元格,viewcontroller 就会弹出。这是我的 tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 方法的代码:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //previously written code
    navigationController?.popViewController(animated: true)
}

一切正常,除了一种情况:加载视图后,我尝试立即按下任何单元格。在那种情况下 popViewController 没有执行,我得到这个错误:

popViewControllerAnimated: called on UINavigationController while an existing transition or presentation is occurring; the navigation stack will not be updated.

我知道,这个问题之前出现在 Whosebug 上,但我没有找到其他解决方案,除了:

DispatchQueue.main.asyncAfter(deadline: .now() + //time) {
    navigationController?.popViewController(animated: true)
}

效果很好,但在按下 tableview 单元格时我不需要延迟。演示一结束,popViewController 就会按要求工作,不需要延迟执行。

还有其他方法可以实现吗?或者以某种方式在转换准备就绪时收到通知,以便我可以在之后弹出?

您可以使用 UIViewControllertransitionCoordinator

它的 documentation 说:

When a presentation or dismissal is in progress, this method returns the transition coordinator object associated with that transition. If there is no in-progress transition associated with the current view controller, UIKit checks the view controller’s ancestors for a transition coordinator object and returns that object if it exists. You can use this object to create additional animations and synchronize them with the transition animations.

let completion = {
    navigationController?.popViewController(animated: true)
}

guard let coordinator = transitionCoordinator else {
    completion()
    return
}

coordinator.animate(alongsideTransition: nil) { _ in
    completion()
}