简体   繁体   中英

Get selected item from picker | SwiftUI

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

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)")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM