ASCollectionView icon indicating copy to clipboard operation
ASCollectionView copied to clipboard

Workaround: EnvironmentObject missing

Open apptekstudios opened this issue 5 years ago • 1 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

apptekstudios avatar Apr 08 '20 11:04 apptekstudios

+1 seeing same issue

Harout360 avatar Jul 22 '20 01:07 Harout360