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.
Asked
Active
Viewed 98 times
0
-
Please paste your code directly in the question. Do not post links to GitHub. – pawello2222 Jul 09 '20 at 23:17
-
Understood. I didn’t know how to paste code in the question and make it look “good”, that’s why I uploaded the project in GitHub. I will procure not do it again. – Byto H Jul 09 '20 at 23:26
-
1You can read more here: [How do I format my code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) – pawello2222 Jul 09 '20 at 23:30
1 Answers
1
You can replace your ForEach
loop in the ContentView
with:
// 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)
}
}
Then use the index
in the DetailView
to access the binding from the @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()
}
}
}

pawello2222
- 46,897
- 22
- 145
- 209