Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set rootViewController in Scene Delegate iOS 13

Tags:

uikit

swift

ios13

Before changes in UIKit iOS 13 how I can set rootViewController at SceneDelegate?

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    @available(iOS 13.0, *)
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }

    }
like image 286
Vinicius Mangueira Avatar asked Oct 01 '19 15:10

Vinicius Mangueira


People also ask

What is the use of scene delegate in iOS?

Using Scene Delegatesplist opts your app into supporting scenes. The scene delegate, not the app delegate, now owns the window. In the UIKit app template, “Enable Multiple Windows” defaults to NO . You should change this to YES if you want to support multiple windows on the iPad.


2 Answers

FYI since SwiftUI doesn't use storyboards if you just make a new SwiftUI project it will give you the code; all you need to do is replace the UIHostingViewController with your desired root VC like this:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

  var window: UIWindow?

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = MyRootViewController()
        self.window = window
        window.makeKeyAndVisible()
    }
  }
like image 165
Josh Homann Avatar answered Sep 21 '22 14:09

Josh Homann


If you ever find yourself needing to access the window from the delegate (both iOS12 & iO13)to change the rootviewcontroller here's a couple of extensions I use:

   extension UIViewController {
        var appDelegate: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    var sceneDelegate: SceneDelegate? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
            let delegate = windowScene.delegate as? SceneDelegate else { return nil }
         return delegate
    }
}

extension UIViewController {
    var window: UIWindow? {
        if #available(iOS 13, *) {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                let delegate = windowScene.delegate as? SceneDelegate, let window = delegate.window else { return nil }
                   return window
        }
        
        guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else { return nil }
        return window
    }
}
like image 27
Larry Mickie Avatar answered Sep 22 '22 14:09

Larry Mickie