Add new Element in Picker in SwiftUI
Asked Answered
S

2

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 :)

Sweeting answered 17/9, 2019 at 5:22 Comment(0)
L
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"
Latham answered 17/9, 2019 at 5:47 Comment(3)
I tried your tip, but selectedValue is not updated ?Sweeting
Then you should change the selectedValue type and value to match with the dataSource. Answer updated.Latham
ahah, it's logic, Thank you.Sweeting
S
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))
    }
}
Sfax answered 21/9, 2020 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.