Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an Environment Object in preview

Tags:

swift

swiftui

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?

like image 247
G. Marc Avatar asked Sep 04 '19 05:09

G. Marc


People also ask

What is an environment object?

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.

When should you assign a value to an @EnvironmentObject property?

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.

What is the difference between an @environment property and an @EnvironmentObject property?

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.


1 Answers

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())
        }
    }
like image 187
Ved Rauniyar Avatar answered Sep 23 '22 11:09

Ved Rauniyar