0

It seems that certain SwiftUI views create new environment contexts, such as NavigationLink. None of the environment is available in the new view.

As a workaround, I've been just manually forwarding through environment variables, like this:

struct ExampleView: View {
    @EnvironmentObject var foo: UserStore
    @EnvironmentObject var bar: UserStore

    var body: some View {
        NavigationLink(destination:
            SomeOtherView()
                .environmentObject(self.foo)
                .environmentObject(self.bar)
        ) {
            Text("Open View")
        }
    }
}

However this seems broken, as it violates the purpose of the environment. Also, it's confusing because it's not clear (or documented?) where these boundaries are and it causes a runtime error when a view depends on a missing EnvironmentObject.

Is there a better way to do this?

Similarly, I want to create a wrapper UIViewControllerRepresentable that can contain SwiftUI children (via UIHostingController) and I would like those children to have access to the environment as well.

Wil Gieseler
  • 1,893
  • 1
  • 17
  • 18

0 Answers0