2

I can't find how to add some element in a picker view in SwiftUI, in my sample, I want add "Z" value in picker when I click the button.

struct ContentView: View {
@State var values: [String] = ["A", "B", "C"]

@State private var selectedValue = 0

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $selectedValue, label: Text("Value")) {
                    ForEach(0 ..< values.count) {
                        Text(self.values[$0])

                    }
                }
            }
            Button(action: {
                self.values.append("Z")
            }, label: {
                Text("Add")
            })
        }.navigationBarTitle("Select a value")

    }
}

When I click on the button, Z is added to "values" array but Picker is not refreshed.

Thank you :)

2 Answers 2

4

You must identify values by id for SwiftUI to make it's changes detectable:

ForEach(0 ..< self.values.count, id: \.self) {
    Text(self.values[$0])
}

This way SwiftIU knowns it should rebuild the picker on change.

Tip: You can use elements directly like this:

ForEach(values, id: \.self) {
    Text($0)
}

Don't forget to change the selectedValue type and value to match with the dataSource IF you followed the tip above:

@State private var selectedValue = "A"
3
  • I tried your tip, but selectedValue is not updated ?
    – ppmax
    Commented Sep 17, 2019 at 9:33
  • Then you should change the selectedValue type and value to match with the dataSource. Answer updated. Commented Sep 17, 2019 at 9:47
  • ahah, it's logic, Thank you.
    – ppmax
    Commented Sep 17, 2019 at 12:12
0

Change selectedValue from int to String

@State private var selectedValue = "A"

add the parameter id and the tag modifier

Picker(selection: $selectedValue, label: Text("Value")) {
    ForEach(values, id: \.self) {
        Text($0).tag(String($0))
    }
}

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