swift - How to bind data between views using @EnviromentObject?
问题描述
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.
解决方案
您可以将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()
}
}
}
推荐阅读
- mysql - Laravel:hasManyThrough 关系获取多对多表值
- python - 我们如何在 Open CV 中创建一个轨迹栏,以便我可以使用它跳到视频的特定部分?
- php - 引导崩溃:显示一个隐藏另一个
- ssl - 如何通过 SSL/TLS 连接 Thingsboard 和 Thingsboard 物联网网关?
- php - 检查队列返回状态
- jakarta-ee - 如何在生产中禁用 swagger-ui(Thorntail)?
- ssl - Websphere trust.p12 vs cacert 存储
- if-statement - MultiWayIf 和经典守卫有什么区别?
- sql - JPARepository findAllByUsername 返回 null 但数据存在
- c# - 用 3D 高斯拟合星光