single function to dismiss all open view controllers

醉酒当歌 提交于 2019-11-27 07:12:17

You can call :

self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)

Should dismiss all view controllers above the root view controller.

Updated answer for Swift 3.2 and swift 4

self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)

and when you use navigationController

self.navigationController?.popToRootViewController(animated: true)

Swift 4:

To dismiss any unwanted residue Modal ViewControllers, I used this and worked well without retaining any navigation stack references.

UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)

self.view.window! did crash for my case possibly because its a Modal screen and had lost the reference to the window.

Swift3

navigationController?.popToRootViewControllerAnimated(true)
Nitin Alabur

Take a look at how unwind segues work. Its super simple, and lets you dismiss/pop to a certain viewcontroller in the heirarchy, even if it consists of a complex navigation (nested pushed and or presented view controllers), without much code.

Here's a very good answer (by smilebot) that shows how to use unwind segues to solve your problem https://stackoverflow.com/a/27463286/503527

Pardeep Kumar

works for Swift 3.0 +

self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)

Swift Used this to jump directly on your ROOT Navigation controller.

self.navigationController?.popToRootViewController(animated: true)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!