如何为 swiftUI 设置初始视图控制器

Nic*_*vit 2 swift swiftui

我通常使用情节提要通过单击属性检查器将视图控制器设置为初始视图控制器。

如何在 swift UI 中设置初始视图控制器?

系统信息:Swift 5,Xcode 11.3.1。

Pia*_*kaa 7

在 SceneDelegate.swift 中

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    let contentView = ContentView().environment(\.managedObjectContext, context)

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
    }
}
Run Code Online (Sandbox Code Playgroud)

将行更改let contentView = ContentView()...YourInitialView()...

结果应该是这样的

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // change this line to your initial view controller class name
    let contentView = YourInitalView().environment(\.managedObjectContext, context)
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你不知道我花了多长时间才找到这个 (2认同)