My view needs an environment object which is set in the SceneDelegate by adding it to the window.rootViewController. How can I set an environment object to be used for the preview?
An @EnvironmentObject is an object living in the current environment, available to read whenever needed. An environment object is defined at a higher-level view, and can any child view can access it if needed.
Just like @ObservedObject , you never assign a value to an @EnvironmentObject property. Instead, it should be passed in from elsewhere, and ultimately you're probably going to want to use @StateObject to create it somewhere. However, unlike @ObservedObject we don't pass our objects into other views by hand.
SwiftUI gives us both @Environment and @EnvironmentObject property wrappers, but they are subtly different: whereas @EnvironmentObject allows us to inject arbitrary values into the environment, @Environment is specifically there to work with SwiftUI's own pre-defined keys.
This userData property gets its value automatically, as long as the environmentObject(_:)
modifier has been applied to a parent.
struct UserList: View {
@EnvironmentObject var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Users Fav only")
}
ForEach(landmarkData) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
UserRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Users"))
}
}
}
struct UserList_Previews: PreviewProvider {
static var previews: some View {
UserList()
.environmentObject(UserData())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With