Workaround: EnvironmentObject missing
apptekstudios opened this issue · comments
The issue
Fatal error: No ObservableObject of type _________ found. A View.environmentObject(_:) for _________ may be missing as an ancestor of this view.
Situation that causes crash:
When using a view type that contains and uses an @EnvironmentObject var
inside an ASCollectionView cell.
eg (pseudocode):
struct YourCellView: View {
@EnvironmentObject var test: TestObject
var body: some View { ... }
}
Why isn't it working?
SwiftUI intermittently attempts to access the view's body before it sets the EnvironmentObject. This leads to a crash.
Notably, EnvironmentObjects are not propagating correctly for SwiftUI's own .sheet
modifier either. Hopefully this issue will be addressed in future SwiftUI versions.
Workaround
Pass your environment object directly to your cell content. eg:
struct ContentView: View {
@EnvironmentObject var yourObject: ObjectType
var body: some View {
ASCollectionView {
ASCollectionViewSection(...) { item in
YourCellView("Your cell contents")
.environmentObject(self.yourObject)
}
}
}
}
Previous discussion: #59, thanks @ryangittings, @kerrmarin
+1 seeing same issue