I’m practicing how to bind data using @EnvironmentObject by making a simple practice app. The main view of the app is a simple list with a title in each cell. By clicking the cell, it will present the detail view. In the detail view is a TextField that can change the title of the cell in the main view. I can’t figure out how to bind the textField with the title of the cell.
问问题
68 次
1 回答
1
您可以将ForEach
循环替换ContentView
为:
// iterate through indices of the `store.items` array
ForEach(0..<store.items.count, id:\.self) { index in
// pass the `index` to the `DetailView`
NavigationLink(destination: DetailView(index: index)) {
Text(self.store.items[index].title)
}
}
然后使用index
inDetailView
访问绑定@EnvironmentObject
:
struct DetailView: View {
@EnvironmentObject var store: CPStore
// item index
let index: Int
var body: some View {
VStack {
// now you can access the item binding
TextField("New title", text: $store.items[index].title)
.padding(5)
.frame(height: 50)
.overlay(Rectangle().stroke(Color.gray, lineWidth: 2))
Spacer()
}
}
}
于 2020-07-09T23:20:07.963 回答