I've got a model with a bool variable that i'll need to bind with a SwiftUI Toggle that is displayed in a List.
import SwiftUI
struct MyModel : Identifiable {
var id: String
var name: String
var notify: Bool
}
import SwiftUI
struct ContentView : View {
var myModels: [MyModel] = []
var body: some View {
NavigationView {
List(myModels) { myModel in
Toggle(isOn: myModel.notify) {
Text(myModel.name)
}
}
.navigationBarTitle(Text("My Models"))
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(tickets: MyModel.mockModels)
}
}
#endif
When the user interacts with the toggle, i'll need the variable `notify` in the model to update.
The only example that i've looked at that implements a Toggle is the WorkingWithUIControls - LandmarkList but i can't seem to get it to work with an array of MyModels.
Any help would be much appreciated.
Okay, I found the solution thanks to Jumhynover at StackOverflow https://stackoverflow.com/a/56616127
This example compiles fine and works as expected.
struct MyModel {
var id: String
var name: String
var notify: Bool
}
import SwiftUI
struct ContentView : View {
@State var myModels: [MyModel] = [
MyModel(id: "1", name: "First Model", notify: false),
MyModel(id: "2", name: "Second Model", notify: true)
]
var body: some View {
NavigationView {
List($myModels.identified(by: \.id.value)) { (myModel : Binding<MyModel>) in
Toggle(isOn: myModel.notify) {
Text(myModel.value.name)
}
}
.navigationBarTitle(Text("My Models"))
}
}
}