0

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?

1
  • 1
    The picker needs a binding in order to modify/set the value with the selection you make. I doubt you'd want to modify anything inside the limits array, so limits doesn't need to be a Binding. Instead, pass the limits array as a constant that you can use for looping (let limits: [Limit]), and accept a @Binding var selectedLimit: Limit? as a second parameter that you can use in your picker: Picker("lower", selection: $selectedLimit). Commented Mar 24 at 0:38

1 Answer 1

0

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]
    }
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.