首页 > 解决方案 > 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.

标签: swiftmvvmdata-bindingswiftuienvironmentobject

解决方案


您可以将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)
    }
}

然后使用indexinDetailView访问绑定@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()
        }
    }
}

推荐阅读