I have an array in SwiftUI where it's an array of a struct that contains a boolean value which is bounded by a Toggle.
struct Blah {
@State var enabled = true
}
struct ContentView: View {
@State public var blahs: [Blah] = [
Blah(false)
]
var body : some View {
List(blahs) { blah in
Toggle(isOn: blah.$enabled)
}
}
}
the blahs arrays will have a button that will append more Blah objects. Xcode is telling me this though:
Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
How should I change this? I don't think I'm applying the concept right.
CodePudding user response:
@State should only be used on a View — or shouldn’t be used inside your model.
Once you’ve removed that, you can use the element binding syntax to get bindings to individual items on the List:
struct Blah : Identifiable {
var id = UUID()
var enabled = true
}
struct ContentView: View {
@State public var blahs: [Blah] = [
Blah(false)
]
var body : some View {
List($blahs) { $blah in
Toggle(isOn: $blah.enabled)
}
}
}
