有没有办法在SceneDelegate中初始化CoreData和EnvironmentObject?

时间:2020-04-28 06:46:44

标签: swift core-data swiftui swiftui-environment environmentobject

如何在scenedelegate根视图中同时初始化ManagedObjectContext和.environmentObject?

我尝试了此代码的所有变体-无效:

let contentView = ContentView().environment(\.managedObjectContext, context)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(UserSettings()))
            self.window = window
            window.makeKeyAndVisible()
        }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这对我来说很好。

let userSettings = UserSettings()

let contentView = ContentView()
        .environment(\.managedObjectContext, context)
        .environmentObject(userSettings)