SwiftUI @Binding doesn't refresh View

后端 未结 1 444
[愿得一人]
[愿得一人] 2021-01-05 03:23

I have a simple master/detail interface where the detail view modifies an item in an array. Using the below, the model is updated properly, but SwiftUI doesn\'t refresh the

相关标签:
1条回答
  • 2021-01-05 04:05

    Here you have a workaround. Use the index, instead of the element when calling ItemDetail. And inside ItemDetail, you use the @EnvironmentObject.

    struct ItemList: View {
        @EnvironmentObject var itemStore: ItemStore
    
        var body: some View {
            NavigationView {
                List(itemStore.items.indices) { index in
                    NavigationLink(destination: ItemDetail(idx: 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 {
        @EnvironmentObject var itemStore: ItemStore
        let idx: Int
    
    
        var body: some View {
            NavigationView {
                Stepper(value: $itemStore.items[idx].inventory) {
                    Text("Inventory is \(self.itemStore.items[idx].inventory)")
                }
                .padding()
                .navigationBarTitle(itemStore.items[idx].name)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题