Coordinator
Coordinator copied to clipboard
EnvironmentObjects not being passed to `.present`-ed views
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.
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
.
Any updates on this?
Any updates on this?