iOS 13: Swift - 'Set application root view controller programmatically' does not work

后端 未结 14 1100
北恋
北恋 2020-12-01 01:43

I have following code in my AppDelegate.swift to setup root view controller for an iOS application. But it does not work. It follows Target structure (defined under General

14条回答
  •  我在风中等你
    2020-12-01 02:20

    First Case

    If major of your project is build in storyboard and before Xcode 11 is used for development and you are not using SwiftUI you want to use your old classes associated with AppDelegate.

    • Then try to remove "Application Scene Manifest" in info.pllist.
    • Remove ScenceDelegate from project completely.

      Then you will able to use your old code.

    Second Case

    If you want to use both Appdelegte and ScenceDelegate then below is working code.

    App Delegate Code:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {   
     if #available(iOS 13.0, *){
        //do nothing we will have a code in SceneceDelegate for this 
    } else {
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let VC = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
        navigationController?.isNavigationBarHidden = true
        navigationController = UINavigationController(rootViewController: VC)
        navigationController?.isNavigationBarHidden = true // or not, your choice.
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window!.rootViewController = navigationController
    }
    return true
    }
    

    ScenceDelegate Code:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let VC = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
        navigationController?.isNavigationBarHidden = true
        guard let windowScene = (scene as? UIWindowScene) else { return }
        self.window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window.windowScene = windowScene
        window.rootViewController = VC
        window.makeKeyAndVisible()
        let appDelegate = UIapplication.shared.delegate as! AppDelegate
        appDelegate.window = window
    }
    

提交回复
热议问题