I would like to construct a form from an array of fields
class Field : Identifiable {
let id = UUID()
var label : String
var value : String
init(label: String, value: String) {
self.label = label
self.value = value
}
}
class App: ObservableObject {
@Published var fields : [Field] = [
Field(label: "PV", value: "100"),
Field(label: "FV", value: "0" )]
func update(label: String) {
switch label {
case "PV" : fields[0].value = calcPV()
case "FV" : fields[1].value = calcFV()
default: break
}
}
}
I am trying to use a ForEach iterator in the View.
struct ContentView: View {
@EnvironmentObject var app: App
var body: some View {
Form {
ForEach(app.fields) { field in
HStack {
Button(action: { self.app.update(label: field.label) } ) {Text(field.label)}
TextField("0", text: field.value) // error
}
}
}
}
}
This code results in the error message Cannot convert value of type 'String' to expected argument type 'Binding<String>' where I try to pass field.value into TextField().
I haven't been able to find a way to create a Binding to pass to TextField().
I can get the wanted behaviour by explicitly calling TextField("0", text: self.$app.fields[1].value) but want to be able to do this with the ForEach so that I can construct a generic form from an array.