Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
Byoth Avatar asked Nov 16 '17 05:11

Byoth


People also ask

How do you dismiss a modal view controller?

According to the View Controller Programming guide for iPhone OS, this is incorrect when it comes to dismissing modal view controllers you should use delegation. So before presenting your modal view make yourself the delegate and then call the delegate from the modal view controller to dismiss.

How to go back to root view controller in Salesforce?

If you are working with simple push navigation controller and you want to go back to root view controller then you simply have to write _ = self.navigationController?.popToRootViewController (animated: true)

How do I dismiss the wrong view controller?

For reference, be aware that you might be dismissing the wrong view controller. For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.

How do you dismiss a modal from another modal?

For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.

How do I dismiss a view using the assistant editor?

1 embed the View you want to dismiss in a NavigationController 2 add a BarButton with "Done" as Identifier 3 invoke the Assistant Editor with the Done button selected 4 create an IBAction for this button 5 add this line into the brackets:#N#self.dismissViewControllerAnimated (true, completion: nil) More ...


1 Answers

Try This :

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

it should dismiss all view controllers above the root view controller.

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)     } } 

It would dismiss all viewControllers until it has a presentingController.

Edit : if you want to dismiss/pop pushed ViewControllers you can use

self.navigationController?.popToRootViewController(animated: true) 

Hope it helps.

like image 81
Agent Smith Avatar answered Sep 18 '22 18:09

Agent Smith