Freddy Benson
Freddy Benson

Reputation: 775

How do I check if view controller is initial view controller? (SWIFT 3)

In the storyboard, there's a property in the inspector pane which says "Is Initial View Controller". How do I access this property programmatically? I don't want to change it. I just want to check if the view controller is currently the initial view controller. I've specified conditions in the AppDelegate under which it should turn the view controller into the root view controller. Once it actually is the root view controller, I want to run some code from the view controller itself (but ONLY when it IS the root view controller). So I can't just run the code from the ViewDidLoad method. I want to check if the view controller is the root view controller first, and if it is, THEN I want to run some code. Any ideas?

Upvotes: 1

Views: 1783

Answers (1)

JAB
JAB

Reputation: 3235

The initial view controller from a storyboard is not the same as the root view controller for the app. You may have multiple storyboards, for instance, each with their own initial view controllers. Some piece of code may have changed the current rootViewController as well, making it different from the initial view controller launched from the app.

To check if a current view controller is the root view controller, use this:

    if self == UIApplication.shared.keyWindow?.rootViewController {
        /*do stuff*/
    }

Be careful about where you place this, though. I would do the check in viewWillAppear or viewDidAppear, instead of viewDidLoad.

Upvotes: 2

Related Questions