【问题标题】:Get selected item from picker | SwiftUI从选择器中获取所选项目 | SwiftUI
【发布时间】:2021-10-22 08:16:15
【问题描述】:

我想从 Picker 中获取所选项目以更新 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())

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    这是一个简单的正确方法示例,这里不需要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)")})
        }
    }
    

    【讨论】:

    • 非常感谢,但在接受您的回答之前,您能否将 PickerStyle 放在 onChange 旁边,因为如果您在 PickerStyle 之后添加 OnChange,UI 会出现一些问题,感谢您的宝贵时间:-)跨度>
    • @GSepetadelis:不客气。你可以这样做,它没有任何尊重!
    【解决方案2】:

    您不应使用索引,但您的 ForEach 中的数组中的对象不需要 onTapGesture,传递给 selection 的变量将保存选定的值。

    类似的东西

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多