如何在Scene Delegate iOS 13中设置rootViewController

时间:2019-10-01 15:43:43

标签: swift uikit 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 }

    }

4 个答案:

答案 0 :(得分:4)

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

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()
    }
  }

答案 1 :(得分:3)

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

import { Link } from '@reach/router'

答案 2 :(得分: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
}

here所示。

答案 3 :(得分:0)

如果您不需要支持多窗口支持,请忽略它。我跟进this answer

使用它启动新项目时,它会自动创建清单和SceneDelegate类。忽略多窗口支持后,您可以像以前一样再次使用应用程序委托窗口。