如何在预览中设置环境对象

时间:2019-09-04 05:27:06

标签: swiftui

我的视图需要一个环境对象,该对象可以通过将其添加到window.rootViewController中来在SceneDelegate中设置。如何设置用于预览的环境对象?

2 个答案:

答案 0 :(得分:1)

您使用.environmentObject(_ :)修饰符将其添加:

struct ContentView_Previews: PreviewProvider {

    static var previews: some View {
        ContentView()
            .environmentObject(YourObject())
    }
}

答案 1 :(得分:1)

只要将 environmentObject(_:) 修饰符应用于父级,此userData属性就会自动获取其值。

 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())
            }
        }