Thomas Thomas - 1 year ago 137
Swift Question

Swift - Change root view controller and dismiss all view controllers

I have an application in which if I already have a user's

saved, I present them with the
and set it as the
, and if not, I present them with the
as the
in my

Inside the
, there is a
screen that I present modally. Inside that settings screen I have a logout button.

My question is, how can set the
as the
, and dismiss all the other controllers in the stack when they click the logout button?

Answer Source

You do it, in essence, exactly the same way you do it in the app delegate. But you are not in the app delegate, so you have to get there in steps:

  1. From the UIApplication class you can get a reference to the shared application object.

  2. From there you can get the app's delegate.

  3. From there you can get the app delegate's window.

  4. Now you can set the window's rootViewController.

The view controller that was the root view controller will vanish in a puff of smoke, along with all its dependent view controllers.

(This, however, is not quite how I would do it. I would have a stable root view controller whose only job is to be custom parent view controller to either the LoginViewController or the MainViewController. I'm not fond of the idea of changing root view controller's in the middle of the app. Still, it's not illegal.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download