I'm trying to make a view with some pickers. The selections should be connected to a property of an binding array:
@Binding var limits: [Limit]
var body: some View {
ForEach(limits) { limit in
HStack {
Text("Value \(limit.value): "
Text("\(limit.from, specifier: "%.1f")")
Text(" - ")
let values = getChangeValuesByLimit(limit: limit)
Picker("lower", selection: ????) {
ForEach(values, id:\.self) { value in
Text("\(value, specifier: "%.1f")").tag(value)
}
}
}
}
}
I don't know how to save the selection (????). How can I achieve this?
Try this approach using ForEach($limits) { $limit in ...}
and Picker("lower", selection: $limit.from) {...}
Since you don't provide a complete code sample, I had to make some assumptions
regarding Limit
, such as struct Limit: Identifiable, Hashable ...
for example. Similarly with what the function getChangeValuesByLimit(...)
returns.
Note of importance, you must have the Picker selection
the same type as the .tag(value)
.
Example code:
struct YourView: View {
@Binding var limits: [Limit]
var body: some View {
ForEach($limits) { $limit in
HStack {
Text("Value \(limit.value): ")
Text("\(limit.from, specifier: "%.1f")")
Text(" - ")
let values = getChangeValuesByLimit(limit: limit)
Picker("lower", selection: $limit.from) {
ForEach(values, id: \.self) { value in
Text("\(value, specifier: "%.1f")")
.tag(value)
}
}
}
}
}
func getChangeValuesByLimit(limit: Limit) -> [Double] {
return [0.0,1.0,2.0,3.0]
}
}