问题
To my knowledge, I should be able to use EnvironmentObject to observe & access model data from any view in the hierarchy. I have a view like this, where I display a list from an array that's in LinkListStore. When I open AddListView and add an item, it correctly refreshes the ListsView with the added item. However, if I use a PresentationButton to present, I have to do AddListView().environmentObject(listStore), otherwise there will be a crash when showing AddListView. Is my basic assumption correct (and this is behavior is most likely a bug) or am I misunderstanding the use of EnvironmentObject?
Basically: @State to bind a variable to a view in the same View (e.g. $text to TextField), @ObjectBinding/BindableObject to bind variables to other Views, and EnvironmentObject to do the same as @ObjectBinding but without passing the store object every time. With this I should be able to add new items to an array from multiple views and still refresh the Lists View correctly? Otherwise I don't get the difference between ObjectBinding and EnvironmentObject.
struct ListsView : View {
@EnvironmentObject var listStore: LinkListStore
var body: some View {
NavigationView {
List {
NavigationButton(destination: AddListView()) {
HStack {
Image(systemName: "plus.circle.fill")
.imageScale(.large)
Text("New list")
}
}
ForEach(listStore.lists) { list in
HStack {
Image(systemName: "heart.circle.fill")
.imageScale(.large)
.foregroundColor(.yellow)
Text(list.title)
Spacer()
Text("\(list.linkCount)")
}
}
}.listStyle(.grouped)
}
}
}
#if DEBUG
struct ListsView_Previews : PreviewProvider {
static var previews: some View {
ListsView()
.environmentObject(LinkListStore())
}
}
#endif
回答1:
From Apple docs EnvironmentObject:
EnvironmentObject A dynamic view property that uses a bindable object supplied by an ancestor view to invalidate the current view whenever the bindable object changes.
It translates as the binding affects the current view hierarchy. My guess is that when you are presenting a new view via PresentationButton, you are creating a new hierarchy, which is not rooted in your view -- the one you have supplied the object to. I'd guess the workaround here is to add the object to the "global" environment by implementing a struct that confirms to the EnvironmentKey
protocol.
来源:https://stackoverflow.com/questions/56508673/environmentobject-in-swiftui