簡體   English   中英

從選擇器中獲取選擇的項目 | SwiftUI

[英]Get selected item from picker | 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())

這是正確執行此操作的簡單示例,此處不需要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)")})
    }
}

您不應使用索引,而應使用 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)")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM