Get selected item from picker | SwiftUI

Viewed 796

I want to get the selected item from a Picker to update some data on the Firebase Database, but when i use the onTapGesture is not working

Note: The items inside the picker are Strings

My Code:

            Picker(selection: $numUnitIndex, label: Text("Numerical Unit: \(numUnit)")) {
                ForEach(0 ..< units.count) {
                    Text(self.units[$0]).tag($0).foregroundColor(.blue)
                        .onTapGesture {
                            //updateUnit(newUnit: self.units[numUnitIndex])
                            print("selected \(numUnitIndex)")
                        }
                }
            }.pickerStyle(MenuPickerStyle())
2 Answers

Here is a simple example of right way of doing this, no need onTapGesture here:

struct ContentView: View {

    let units: [String] = ["", "", "", "", ""]
    @State private var selectedUnit: Int = 0
    
    var body: some View {
        
        Picker(selection: $selectedUnit, label: Text("You selected: \(units[selectedUnit])")) {
            ForEach(units.indices, id: \.self) { unitIndex in Text(units[unitIndex]) }
        }
        .pickerStyle(MenuPickerStyle())
        .onChange(of: selectedUnit, perform: { newValue in print("Selected Unit: \(units[newValue])", "Selected Index: \(newValue)")})
    }
}

You shouldn't use indices but the objects in the array in your ForEach and there is no need for onTapGesture, the variable passed to selection will hold the selected value.

Something like this

let units: [String] = ["a", "b", "c"]
@State private var selectedUnit: String

init() {
    selectedUnit = units.first ?? ""
}

var body: some View {
    VStack {
        Picker("Units", selection: $selectedUnit) {
            ForEach(units, id: \.self) { unit in
                Text(unit)
                    .foregroundColor(.blue)
                    .font(.largeTitle)
            }
        }.pickerStyle(MenuPickerStyle())
        Text("Selected unit is \(selectedUnit)")
    }
}
Related