[英]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我想从选择器中获取所选项目以更新 Firebase 数据库中的一些数据,但是当我使用onTapGesture
时不起作用
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:这是正确执行此操作的简单示例,此处不需要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)")})
}
}
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.您不应使用索引,而应使用 ForEach 数组中的对象,并且不需要 onTapGesture,传递给selection
的变量将保存所选值。
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)")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.