我有几个推送视图控制器的UINavigationController
。
UPD:上次推送的控制器以模态显示另一个控制器。
另外,我在UINavigationControllerDelegate
上有一些逻辑的navigationController:willShowViewController:animated:
。
UPD:导航控制器是其自己的委托。委托是在viewDidLoad
方法中设置的。
问题尝试从显示的视图控制器以编程方式关闭所有控制器时,会升高:
// Close all controllers in navigation stack
presentingViewController?.navigationController?.popToRootViewController(animated: true)
// Close presented view controller
dismiss(animated: true, completion: nil)
不调用
navigationController:willShowViewController:animated:
方法。但是,当我在没有控制器的情况下执行相同操作时,就会调用它(感谢@donmag,例如可以工作的项目)。在SO中搜寻答案或类似问题,但一无所获,有什么想法吗?
最佳答案
在您的“展示” VC中,您想要实现一个委托/协议模式,以便您的“展示” VC可以回叫并执行dismiss和popToRoot ...
// protocol for the presented VC to "call back" to the presenting VC
protocol dismissAndPopToRootProtocol {
func dismissAndPopToRoot(_ animated: Bool)
}
// in the presenting VC
@IBAction func presentTapped(_ sender: Any) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "presentMeVC") as? PresentMeViewController {
// Assign the delegate when instantiating and presenting the VC
vc.dapDelegate = self
present(vc, animated: true, completion: nil)
}
}
func dismissAndPopToRoot(_ animated: Bool) -> Void {
// this will dismiss the presented VC and then pop to root on the NavVC stack
dismiss(animated: animated, completion: {
self.navigationController?.popToRootViewController(animated: animated)
})
}
// in the presented VC
var dapDelegate: dismissAndPopToRootProtocol?
@IBAction func dismissTapped(_ sender: Any) {
// delegate/protocol pattern - pass true or false for dismiss/pop animation
dapDelegate?.dismissAndPopToRoot(false)
}
这是一个完整的演示项目:https://github.com/DonMag/CustomNavController