我有一个简单的主/详细界面,其中详细视图修改数组中的项目。使用下面的方法,模型会正确更新,但 SwiftUI 不会刷新视图以反映更改。
模型:
struct ProduceItem: Identifiable {
let id = UUID()
let name: String
var inventory: Int
}
final class ItemStore: BindableObject {
var willChange = PassthroughSubject<Void, Never>()
var items: [ProduceItem] { willSet { willChange.send() } }
init(_ items: [ProduceItem]) {
self.items = items
}
}
显示 ProduceItems 列表的主视图(ItemStore 被插入到 SceneDelegate 中的环境中):
struct ItemList: View {
@EnvironmentObject var itemStore: ItemStore
var body: some View {
NavigationView {
List(itemStore.items.indices) { index in
NavigationLink(destination: ItemDetail(item: self.$itemStore.items[index])) {
VStack(alignment: .leading) {
Text(self.itemStore.items[index].name)
Text("\(self.itemStore.items[index].inventory)")
.font(.caption)
.foregroundColor(.secondary)
}
}
}
.navigationBarTitle("Items")
}
}
}
详细视图,可让您更改项目的库存值:
struct ItemDetail: View {
@Binding var item: ProduceItem
var body: some View {
NavigationView {
Stepper(value: $item.inventory) {
Text("Inventory is \(item.inventory)")
}
.padding()
.navigationBarTitle(item.name)
}
}
}
在 ItemDetail 视图中点击步进器会修改商店中的项目,但步进器的文本不会更改。导航回列表确认模型已更改。此外,我确认商店致电willChange.send()
其出版商。我会假设send()
调用会更新环境中的 ItemStore,并且@Binding
应该将更改通知详细视图的属性并刷新显示(但事实并非如此)。
我尝试更改 ItemDetail 的 item 属性以使用@State
:
@State var item: ProduceItem = ProduceItem(name: "Plums", inventory: 7)
在这种情况下,模型是在使用步进器时更新的,并且视图被刷新,显示更新的库存。谁能解释为什么使用该@Binding
属性不会刷新界面,但本地@State
属性会?