Is it possible to set initial view controller with code?

Is it possible to use code to decide which view controller is the initial view controller, so that the code decides in run time which is the first view controller to present?

Accepted Reply

In appDelegate, didFinishLaunching, before returning true, add


        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "NextVC")
        self.window?.rootViewController = initialViewController


You must have defined the storyboard ID of the controller as NextVC (or any other name)


However, if you had defined an unwind segue from the nextVC to the first, that will not work after the change.

Replies

In appDelegate, didFinishLaunching, before returning true, add


        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "NextVC")
        self.window?.rootViewController = initialViewController


You must have defined the storyboard ID of the controller as NextVC (or any other name)


However, if you had defined an unwind segue from the nextVC to the first, that will not work after the change.

I tried your suggestion with the following code:


        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        guard let initialViewController = storyboard.instantiateViewController(withIdentifier: "viewController") as? ViewController else {
            
            fatalError("Unable to instantiate an ViewController from the storyboard")
            
        }

        self.window?.rootViewController = initialViewController


I got an error saying: "[Application] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?"

I fixed the problem. Even though I'm using code, there still has to be a view controller set as an initial view controller in interface builder.


Thanks for the help.