SwiftUIX / Coordinator

A declarative navigation API for SwiftUI.
MIT License
252 stars 21 forks source link

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

Closed nsillik closed 9 months ago

nsillik commented 2 years ago

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 commented 2 years ago

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.

fampaySiddharth commented 1 year ago

Any updates on this?

gabrielribeiro commented 11 months ago

Any updates on this?