如何在 Scene Delegate iOS 13 中设置 rootViewController

Vin*_*ira 10 uikit swift ios13

在 UIKit iOS 13 更改之前,如何在 SceneDelegate 设置 rootViewController?

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 }

    }
Run Code Online (Sandbox Code Playgroud)

Jos*_*ann 29

仅供参考,因为 SwiftUI 不使用故事板,如果你只是创建一个新的 SwiftUI 项目,它会给你代码;您需要做的就是将 UIHostingViewController 替换为您想要的根 VC,如下所示:

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()
    }
  }
Run Code Online (Sandbox Code Playgroud)


Lar*_*kie 9

如果您发现自己需要从委托(iOS12 和 iO13)访问窗口以更改 rootviewcontroller,请使用以下几个扩展:

   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
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*lar 0

像这样:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

   var window: UIWindow?
   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 _ = (scene as? UIWindowScene) else { return }

        let rootVC = self.window?.rootViewController 
    }
    // ... the rest of SceneDelegate
}
Run Code Online (Sandbox Code Playgroud)

正如这里所见。