简体   繁体   中英

How do you add .environment(...) to your ContentView() when you don't have a scene delegate (SwiftUI)?

Normally when you create a new swiftUI app, you have this scene delegate:

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

and you have your contentView:

struct ContentView: View {}

I would like to add.environment to contentView as follows:

ContentView()
.environment(\.managedObjectContext, yourCoreDataContext)

But as I initially created my app as a swift UIKit app I don't have this scene delegate to do this. How can I add the environment?

(I am using UIHostingController to show my swiftUI view)

If you created UIKit project with CoreData then view context is in AppDelegate, so the code of presenting controller with ContentView might look like

    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        let viewContext = delegate.persistentContainer.viewContext
        let controller = UIHostingController(rootView:
            ContentView()
            .environment(\.managedObjectContext, viewContext)
        )
        self.present(controller, animated: true)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM