1

I am trying to build a dynamic Picker with a segmented style that re-renders itself based on user input.

So in other words, every time the user adds a value to the filterValues array the segmented picker should re-render.

This what I tried and not working:enter image description here

struct ContentView: View {
   @State private var items = [Item]()
   @State private var filterValueIndex = 0
   @State private var filterValues: [Int] = [1, 2, 3, 5]

   var body: some View {
       Picker("Filter", selection: $filterValueIndex) {
            ForEach(0 ..< filterValues.count) {
                Text("\(filterValues[$0])")
            }
        }
       .pickerStyle(SegmentedPickerStyle())
   }
}

1 Answer 1

1

We need to use dynamic ForEach for that as below (tested with Xcode 12.1 / iOS 14.1)

    Picker("Filter", selection: $filterValueIndex) {
            ForEach(filterValues.indices, id: \.self) {    // << here !!
                 Text("\(filterValues[$0])")
            }
      }
    .pickerStyle(SegmentedPickerStyle())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.