Studing SwiftUI in Apple's HandlingUserInput, I'm blocked in this error:
No ObservableObject of type UserData found. A View.environmentObject(_:) for UserData may be missing as an ancestor of this view.
The code is:
final class UserData: ObservableObject {
@Published var showFavoritesOnly = false
@Published var landmarks = landmarkData
}
struct LandmarkList: View {
@EnvironmentObject var userData: UserData
var body: some View {
NavigationView {
List(landmarkData) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
LandmarkList()
.environmentObject(UserData())
}
}
".environmentObject(UserData())" is present in the preview.
"@EnvironmentObject var userData: UserData" in the View.
But the use of userData (if !self.userData.showFavoritesOnly) cause the fatal error.
Can someone help me in undertanding how to proceed?
Have you followed Step 4 - Section 5 of the tutorial?
> In
SceneDelegate.swift
, add the environmentObject(_:)
modifier to the LandmarkList
.".environmentObject(UserData())" is present in the preview.
Preview is just used for previewing, you need to put `environmenObject(UserData())` somewhere in an actual app.