在SwiftUI 2.0中添加EnvironmentObject

时间:2020-07-30 12:00:43

标签: swift swiftui

由于SwiftUI 2.0不再具有AppDelegate和SceneDelegate,因此应该在哪里设置EnvironmentObjects?

这是以前的操作方式,我现在必须在哪里添加它们?

window.rootViewController = UIHostingController(rootView: ContentView()
                             .environmentObject(settings))

1 个答案:

答案 0 :(得分:3)

尝试以下操作:

@main
struct TestApp: App {
    @StateObject var settings: Settings = ... // init here

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(settings)
        }
    }
}