Programmatically set the initial view controller using Storyboards

前端 未结 22 2363
感情败类
感情败类 2020-11-22 15:00

How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may

22条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 15:27

    SWIFT 5

    If you don't have a ViewController set as the initial ViewController in storyboard, you need to do 2 things:

    1. Go to your project TARGETS, select your project -> General -> Clear the Main Interface field.
    2. Always inside project TARGETS, now go to Info -> Application Scene Manifest -> Scene Configuration -> Application Session Role -> Item0 (Default Configuration) -> delete the storyboard name field.

    Finally, you can now add your code in SceneDelegate:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let windowScene = (scene as? UIWindowScene) else { return }
    
        window = UIWindow(windowScene: windowScene)
    
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        // Make sure you set an Storyboard ID for the view controller you want to instantiate
        window?.rootViewController = storyboard.instantiateViewController(withIdentifier: identifier)
        window?.makeKeyAndVisible()
    
    }
    

提交回复
热议问题