Cloy
Cloy

Reputation: 2181

Dismiss View Controller to Particular View Controller

My View Contollers Login -> Main Menu -> A -> B -> C -> D

How do i dimiss all view controllers and go back to main menu

For Logout from my view controllers I am doing the following which takes back to Login

func logout{

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

Now what i am doing is this

class AppDelegate: UIResponder, UIApplicationDelegate {
     var viewControllerStack: [BaseViewController]!
}

override func viewDidLoad() {
    super.viewDidLoad()
    super.appDelegateBase.viewControllerStack.append(self)  
}

func go_To_MainMenu(){
    var countOfNumberOfViewCOntrollers = self.appDelegateBase.viewControllerStack.count 

        switch countOfNumberOfViewCOntrollers{

             self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
            break;
        case 2:

            self.presentingViewController?.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
            break;
   }
}

Upvotes: 6

Views: 6959

Answers (6)

RAHUL NIMJE
RAHUL NIMJE

Reputation: 91

Swift 5

This works for me

var presentingViewController = PresentingViewController()
self.dismiss(animated: false) {
    presentingViewController.dismiss(animated: false, completion: nil)
}

Upvotes: 1

El_boogy
El_boogy

Reputation: 155

This worked for me,

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

Upvotes: 0

Norolim
Norolim

Reputation: 956

You can use Unwind Segue if MainMenu isn't your rootViewController. Look at this article, hope it will help. Unwind Segue with Swift

Upvotes: 2

mag_zbc
mag_zbc

Reputation: 6982

Instead of presenting/dismissing you can use UINavigationController to push/pop view controllers. That way you can use UINavigationController's popToViewController(_:animated:) which can pop to any view controller in navigation stack.

Upvotes: 1

Pochi
Pochi

Reputation: 13459

If your MainMenu VC always comes AFTER your Login VC, you could simply use the same method:

To MainMenu:

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

Upvotes: 8

amit
amit

Reputation: 425

Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.

Upvotes: 0

Related Questions