Swift - 如何关闭所有视图控制器以返回 root [英] Swift - How to dismiss all of view controllers to go back to root
问题描述
我希望我的应用可以在每次用户需要时转到第一个视图控制器.
I want a my app can go to a first view controller when every time users want it.
所以我想创建一个函数来关闭所有的视图控制器,无论它是在导航控制器中推送还是以模态呈现或打开任何方法.
So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.
我尝试了各种方法,但我肯定没有关闭所有的视图控制器.有没有简单的方法?
I tried various ways, but I failed to dismiss all the view controllers certainly. Is there an easy way?
推荐答案
试试这个:
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
它应该关闭根视图控制器上方的所有视图控制器.
it should dismiss all view controllers above the root view controller.
如果这不起作用,您可以通过运行像这样的 while 循环来手动执行此操作.
If that doesn't work than you can manually do that by running a while loop like this.
func dismissViewControllers() {
guard let vc = self.presentingViewController else { return }
while (vc.presentingViewController != nil) {
vc.dismiss(animated: true, completion: nil)
}
}
它会关闭所有的 viewController 直到它有一个presentingController.
It would dismiss all viewControllers until it has a presentingController.
如果你想关闭/弹出推送的ViewControllers,你可以使用
Edit : if you want to dismiss/pop pushed ViewControllers you can use
self.navigationController?.popToRootViewController(animated: true)
希望有帮助.
这篇关于Swift - 如何关闭所有视图控制器以返回 root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!