2020年1月10日金曜日

EnvironmentObject Swift

EnvironmentObject in Swiftaccording to apple's Document A dynamic view property that uses a bindable object supplied by an ancestor view to invalidate the current view whenever the bindable object changes.

Declaration

@frozen @propertyWrapper struct EnvironmentObject<ObjectTypewhere ObjectType : ObservableObject

what does that mean ?


my understanding is that variable wrapped @EnvironmentObject can be shared 
across all views and update view when the variable is updated.
This is like the way React/Redux store doing.
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 {
                Toggle(isOn: $userData.showFavoritesOnly  , label: {Text("Favorites only")})
                ForEach(userData.landmarks) { landdata in
                    if (!self.userData.showFavoritesOnly || landdata.isFavorite) {
                        NavigationLink(destination: ContentView(landmark:   landdata)) {
                            LandmarkRow(landmark: landdata)
                            }.navigationBarTitle(Text("Landmark"))
                        }
                    }
                }
        }
    }
}


0 件のコメント:

コメントを投稿