Swift - How to dismiss all of view controllers to

2020-05-13 09:23发布

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?

12条回答
疯言疯语
2楼-- · 2020-05-13 09:54

The best and prefered way to do this is to create an unwind segue. Just follow this documentation https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/UsingSegues.html. It can de done in code or through the interface builder.

查看更多
孤傲高冷的网名
3楼-- · 2020-05-13 09:56
 func  dismiss_all(view: UIView){
   view.window!.rootViewController?.dismiss(animated: true, completion: nil)

 }
查看更多
老娘就宠你
4楼-- · 2020-05-13 09:57

To achieve what you want, modify your navigation stack, then do popViewController.

let allControllers = NSMutableArray(array: navigationController!.viewControllers)
let vcCount = allControllers.count
for _ in 0 ..< vcCount - 2 {
    allControllers.removeObject(at: 1)
}
// now, allControllers[0] is root VC, allControllers[1] is presently displayed VC. write back to nav stack
navigationController!.setViewControllers(allControllers as [AnyObject] as! [UIViewController], animated: false)
// then pop root VC
navigationController!.popViewController(animated: true)

See this for the way to further manipulate the navigation stack. If your topmost VC is modal, dismiss it first before the code above.

查看更多
Animai°情兽
5楼-- · 2020-05-13 09:59

Simply ask your rootViewController to dismiss any ViewController if presenting.

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
   appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
   (appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
}
查看更多
ゆ 、 Hurt°
6楼-- · 2020-05-13 10:00

Pops all the view controllers on the stack except the root view controller and updates the display.

func popToRootViewController(animated: Bool)

But if you want to go to specific controller just use the below function.

func popToViewController(UIViewController, animated: Bool)

Pops view controllers until the specified view controller is at the top of the navigation stack.

查看更多
做自己的国王
7楼-- · 2020-05-13 10:07

Hello everyone here is the answer for Swift-4.

To go back to root view controller, you can simply call a line of code and your work will be done.

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

And if you have the splash screen and after that the login screen and you want to go to login screen you can simply append presentedviewcontroller in the above code.

self.view.window?.rootViewController?.presentedViewController!.dismiss(animated: true, completion: nil)
查看更多
登录 后发表回答