如何关闭当前Presenting Controller并通过Navigation Controller跳转至其他控制器?
嘿,我来帮你搞定这个问题~你当前的代码存在一个关键逻辑坑:当调用dismiss(animated:completion:)完成后,当前控制器已经被从视图层级中移除了,这时候再访问self.navigationController几乎肯定是nil,所以push操作根本执行不了。
下面给你两种靠谱的解决方案:
方案一:借助Presenting Controller的导航栈完成跳转
如果发起present操作的那个控制器本身就在Navigation Controller的栈里,你可以在dismiss的回调中,拿到发起present的控制器的导航控制器来执行push:
self.dismiss(animated: false) { // 安全获取发起present的控制器的导航控制器 guard let presentingNavVC = self.presentingViewController?.navigationController else { print("无法获取导航控制器") return } // 安全实例化目标控制器(避免强制解包崩溃) guard let targetVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as? ViewController else { print("无法实例化目标控制器") return } presentingNavVC.pushViewController(targetVC, animated: false) }
方案二:回到根导航栈后再跳转
如果你的需求是先关闭当前的Presenting Controller,然后回到导航栈的根页面再跳转,可先执行回退操作再push:
self.dismiss(animated: false) { guard let presentingNavVC = self.presentingViewController?.navigationController else { return } // 先回到导航栈的根控制器 presentingNavVC.popToRootViewController(animated: false) // 再push目标控制器 guard let targetVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as? ViewController else { return } presentingNavVC.pushViewController(targetVC, animated: false) }
重要提醒
- 尽量避免使用
as!强制解包,改用as?配合guard let/if let,能有效防止因storyboard ID错误或类型不匹配导致的崩溃。 - 确保
presentingViewController确实属于某个Navigation Controller,如果不是,需要调整视图层级(比如给Presenting Controller套一个Navigation Controller)。
内容的提问来源于stack exchange,提问作者Rizwan Mehmood
相关产品推荐
相关产品推荐

