Latest way to Set A Root View Controller Programmatically in Swift

While trying to set a custom rootViewController in swift with a UIWindow, in the traditional way results in a black screen. The reason is now we need to use UIWindowScene to create a UIWindow instance.

Removing the Main storyboard

In order to remove the main storyboard, we need to do the following steps

  • Delete Main.storyboard file
  • Go to project -> target -> General -> Main interface and set it to blank As shown in image below
removing main storyboard swift

Once we have removed the Main.storyboard, we can now move to the next step

Setting rootViewController programmatically in Swift

Open your SceneDelegate.swift file and change func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) to

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let scene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: scene)  // we are not using frome anymore
        let vc = UIViewController() //Your view controller or navigation controller
        window.rootViewController = vc
        window.makeKeyAndVisible()
        
    }

You are good to go. Hope this helps!!!

A pat on the back !!