Swift 如何使用@EnvironmentObject在视图之间绑定数据?
我正在通过制作一个简单的实践应用程序来练习如何使用@EnvironmentObject绑定数据。应用程序的主视图是一个简单的列表,每个单元格中都有一个标题。通过单击单元,它将显示详图视图。详细视图中有一个文本字段,可以更改主视图中单元格的标题。我不知道如何将文本字段与单元格标题绑定。您可以将Swift 如何使用@EnvironmentObject在视图之间绑定数据?,swift,mvvm,data-binding,swiftui,environmentobject,Swift,Mvvm,Data Binding,Swiftui,Environmentobject,我正在通过制作一个简单的实践应用程序来练习如何使用@EnvironmentObject绑定数据。应用程序的主视图是一个简单的列表,每个单元格中都有一个标题。通过单击单元,它将显示详图视图。详细视图中有一个文本字段,可以更改主视图中单元格的标题。我不知道如何将文本字段与单元格标题绑定。您可以将ContentView中的ForEach循环替换为: // iterate through indices of the `store.items` array ForEach(0..<store.it
ContentView
中的ForEach
循环替换为:
// 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)
}
}
请将您的代码直接粘贴到问题中。不要发布指向GitHub.com的链接。我不知道如何在问题中粘贴代码并使其看起来“好”,这就是为什么我将该项目上传到GitHub。我不会再这样做了。你可以在这里阅读更多内容:
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()
}
}
}