Coordinator icon indicating copy to clipboard operation
Coordinator copied to clipboard

EnvironmentObjects not being passed to `.present`-ed views

Open nsillik opened this issue 2 years ago • 1 comments

I'm having trouble figuring out how to have my environment objects pass along to views presented modally with the .present ViewTransition. I am getting the following error: Fatal error: No ObservableObject of type MyObject found. A View.environmentObject(_:) for MyObject may be missing as an ancestor of this view.

The following reproduces the issue:

import SwiftUI
import Coordinator

enum Route {
  case presentView(AnyView)
}

class AppCoordinator: UIViewControllerCoordinator<Route> {
  override func transition(for route: Route) -> ViewTransition {
    switch route {
    case .presentView(let anyView):
      return .present(anyView)
    }
  }
}

class MyObject: ObservableObject {
  let string = "My Object's String"

  init() {}
}

struct ContentView: View {
  var body: some View {
    ViewA()
      .environmentObject(MyObject())
      .coordinator(AppCoordinator())
  }
}

struct ViewA: View {
  @Coordinator(for: Route.self) var coordinator
  @EnvironmentObject var myObject: MyObject

  var body: some View {
    VStack {
      Button(action: {
        coordinator.trigger(.presentView(AnyView(ViewB())))
      }, label: Text("Press Me"))
      Text(myObject.string)
    }
  }
}

struct ViewB: View {
  @EnvironmentObject var myObject: MyObject

  var body: some View {
    Text(myObject.string)
  }
}

Am I missing some required setup? Or is this not possible, if I must I could make the environment objects that I create singletons, although at least one of them that will be less-than-straightforward.

nsillik avatar Aug 23 '22 19:08 nsillik

Additionally, I've tried following the EnvironmentInsertions code paths, which I assumed were related to this, but I seem to have lost the thread. My coordinator doesn't have anything in self.environmentInsertions.

nsillik avatar Aug 23 '22 19:08 nsillik

Any updates on this?

fampaySiddharth avatar May 29 '23 11:05 fampaySiddharth

Any updates on this?

gabrielribeiro avatar Sep 20 '23 18:09 gabrielribeiro