How to access values from particular item on the list made with ForEach? As you can see I was trying something like this (and many other options):
Text(item[2].onOff ? "On" : "Off")
I wanted to check the value of toggle of 2nd list item (for example) and update text on the screen saying if it's on or off.
And I know that it's something to do with @Binding and I was searching examples of this and trying few things, but I cannot make it to work. Maybe it is a beginner question. I would appreciate if someone could help me.
My ContentView:
struct ContentView: View { // @Binding var onOff : Bool @State private var onOff = false @State private var test = false var body: some View { NavigationView { List { HStack { Text("Is 2nd item on or off? ") Text(onOff ? "On" : "Off") // Text(item[2].onOff ? "On" : "Off") } ForEach((1...15), id: \.self) {item in ListItemView() } } .navigationBarTitle(Text("List")) } } } And ListItemView:
import SwiftUI struct ListItemView: View { @State private var onOff : Bool = false // @Binding var onOff : Bool var body: some View { HStack { Text("99") .font(.title) Text("List item") Spacer() Toggle(isOn: self.$onOff) { Text("Label") } .labelsHidden() } } }
ObservableObjectand pass it between views, so each could modify related properties, and you could use them navigating between views. (@Stateactually is designed to be view-only-thing).