1

I want to change Picker's content dynamically.
But I think you cannot pass Binding property into ForEach.

@Binding var options: [String]
@Binding var selectedIndex: Int

var body: some View {
    Picker(selection: self.$selectedIndex, label: Text("")) {
        ForEach(0..<self.$options.count) { // error: Cannot assign to property: 'count' is a get-only property
            Text(self.options[$0])
        }
    }
}

1 Answer 1

2

Here is a demo of possible solution. Tested with Xcode 11.4 / iOS 13.4

struct TestPickerView: View {
    @Binding var options: [String]
    @Binding var selectedIndex: Int

    var body: some View {
        Picker(selection: self.$selectedIndex, label: Text("")) {
            ForEach(Array(self.options.enumerated()), id: \.element) { index, item in
                Text(item).tag(index)
            }
        }.id(options)     // << important !!
    }
}

Note: a Picker have to be explicitly depend on options to be updated/rebuilt when number of options changed, this is what id is needed for.

1
  • Thank you for your wonderful support. Another problem occured. When I define options as [Int] and select Picker, the Picker pass element itself into selectedIndex even though set .tag(index) Commented Jun 7, 2020 at 13:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.