从选择器中获取选定的项目 | 斯威夫特用户界面

GSe*_*lis 2 ios swift swiftui

我想从选取器中获取所选项目以更新 Firebase 数据库上的一些数据,但是当我使用时onTapGesture不起作用

注意:选择器内的项目是字符串

我的代码:

            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())
Run Code Online (Sandbox Code Playgroud)

use*_*ser 5

这是执行此操作的正确方法的简单示例,此处不需要onTapGesture

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)")})
    }
}
Run Code Online (Sandbox Code Playgroud)