Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does SwiftUI pass EnvironmentObjects between HostingController?

I am trying to implement an Apple Watch app in a similar way as this question: Issues implementing navigation from a main controller to page based controllers in WatchOS using SwiftUI

I am trying to pass data between different HostingControllers. My data is stored in an EnvironmentObject with published properties. If I only use one HostingController, it's fine to share data between the different views. But when using a different HostingController, hosting different views (without segues), I can't find the syntax for using my Environment object from HC1 to HC2, the HC3, etc.

I present the HostingController using this piece of code in my SwiftUI views.

NavigationLink(destinationName: "HC2"){
        Text("Go to HC2")
like image 224
Raphaël Barthomeuf Avatar asked Nov 05 '25 04:11

Raphaël Barthomeuf


1 Answers

Here is possible approach

class AppState: ObservableObject {
    static let shared = AppState()      // shared instance

    @Published var setting: String = "some"
}

class HostingController: WKHostingController<AnyView> {
    override var body: AnyView {
        let contentView = ContentView()
            .environmentObject(AppState.shared)     // << inject !!
        return AnyView(contentView)
    }
}

class HostingController2: WKHostingController<AnyView> {
    override var body: AnyView {
        let contentView = ContentView2()
            .environmentObject(AppState.shared)     // << inject !!
        return AnyView(contentView)
    }
}
like image 54
Asperi Avatar answered Nov 09 '25 10:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!