@Binding and ForEach in SwiftUI
You can use something like the code below. Note that you will get a deprecated warning, but to address that, check this other answer: https://stackoverflow.com/a/57333200/7786555
import SwiftUI
struct ContentView: View {
@State private var boolArr = [false, false, true, true, false]
var body: some View {
List {
ForEach(boolArr.indices) { idx in
Toggle(isOn: self.$boolArr[idx]) {
Text("boolVar = \(self.boolArr[idx] ? "ON":"OFF")")
}
}
}
}
}
In SwiftUI, just use Identifiable structs instead of Bools
struct ContentView: View {
@State private var boolArr = [BoolSelect(isSelected: true), BoolSelect(isSelected: false), BoolSelect(isSelected: true)]
var body: some View {
List {
ForEach(boolArr.indices) { index in
Toggle(isOn: self.$boolArr[index].isSelected) {
Text(self.boolArr[index].isSelected ? "ON":"OFF")
}
}
}
}
}
struct BoolSelect: Identifiable {
var id = UUID()
var isSelected: Bool
}
If also you need to change the number of Toggle
s (not only their values), consider this. BTW, we can omit ForEach
{} block.
struct ContentView: View {
@State var boolArr = [false, false, true, true, false]
var body: some View {
NavigationView {
// id: \.self is obligatory if you need to insert
List(boolArr.indices, id: \.self) { idx in
Toggle(isOn: self.$boolArr[idx]) {
Text(self.boolArr[idx] ? "ON":"OFF")
}
}
.navigationBarItems(leading:
Button(action: { self.boolArr.append(true) })
{ Text("Add") }
, trailing:
Button(action: { self.boolArr.removeAll() })
{ Text("Remove") })
}
}
}