I'm trying to pass an EnvironmentObject to child views but am having no luck with the following code.
struct ContentView: View {
enum MyViews: Int, CaseIterable {
case introView
case viewOne
case viewTwo
var activeView: AnyView {
switch self.rawValue {
case 0: return AnyView(IntroView())
case 1: return AnyView(ViewOne())
case 2: return AnyView(ViewTwo())
default: return AnyView(IntroView())
}
}
@State var pageIndex = 0
func content() -> MyViews? {
let newPage = MyViews.init(rawValue: pageIndex)
return newPage
}
}
var body: some View {
Group {
content()?.activeView // Problem appears to lie here
}
.environmentObject(userData)
}
If I replace content()?.activeView
with a simple view e.g. TestView()
then I'm able to successfully print out the userData variable in TestView(). But as it stands, I get a crash when trying to access userData in ViewOne(), even when ViewOne is identical to TestView().
Any idea what I'm doing wrong?