什么相当于 WindowGroup 中的 'window.rootViewController' - SwiftUI

What is equivalent to 'window.rootViewController' in WindowGroup - SwiftUI

我是 SwiftUI 的新手,遇到了一个问题,我想在应用程序内部发生特定操作时更改根视图。

我在使用SceneDelegate时的处理方式如下

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
       ... // the code of initializing the window

        observeOnChangeWindow()
    }

    func observeOnChangeWindow(){
        NotificationCenter.default.addObserver(self, selector: #selector(self.performChangeWindow), name: Notification.Name(K.changeWindowNotificationName), object: nil)
    }
    
    @objc func performChangeWindow() {
        self.window?.rootViewController = UIHostingController(rootView: SplashScreenView())
    }

但是,我目前没有使用 SceneDelegate,因为我正在使用 WindowGroup

初始化应用程序
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            SplashScreenView()
        }
    }
}

我的问题是: 我现在如何使用 SceneDelegate 执行相同的操作?

在评论和一些教程的帮助下,我找到了解决方案(在 iOS 15、Xcode 13.2.1 上测试):

将以下代码添加到主应用程序启动器。

struct MyApp: App {
    
    @StateObject var appState = AppState.shared
      
    var body: some Scene {
        WindowGroup {
            SplashScreenView().id(appState.environment)
        }
    }
}

然后我创建了 AppState class,这是 class,当更改时我将更改 window。

class AppState: ObservableObject {
    static let shared = AppState()
    @Published var environment = "Production"
}

每当我想更改环境并执行在 UIKit 中更改 window 的相同功能时,请执行以下操作:

AppState.shared.environment = "Pre-Production"