[英]When using a swiftui picker with an array of options. How can I save the selected option rather than the index value to Cloud Firestore?
I'd like to be able to access and use the location.我希望能够访问和使用该位置。 Currently only the index value from the picker is being saved to Cloud Firestore.
目前只有选择器的索引值被保存到 Cloud Firestore。
Here is the picker:这是选择器:
Picker(selection: $viewModel.injury.locationIndex, label: Text("General Location")) {
ForEach(0 ..< locationOptions.count) {
Text(self.locationOptions[$0])
}
Here is the array:这是数组:
var locationOptions = ["🤕 Head", "🦺 Chest", "💪 Right Arm", "💪 Left Arm", "🤚 Right Hand", "✋ Left Hand", "🩲 Waist", "🦵 Right Leg", "🦵 Left Leg", "🦶 Right Foot", "🦶 Left Foot"]
The locationIndex is successfully uploaded to Cloud Firestore: locationIndex 已成功上传到 Cloud Firestore:
import SwiftUI
import Firebase
class InjuryViewModel: ObservableObject {
@Published var injury: Injury = Injury(id: "", userId: "", specificLocation: "", comment: "", active: false, injuryDate: Date(), exercises: "", locationIndex: 0)
private var db = Firestore.firestore()
func addInjury(injury: Injury) {
do{
var addedInjury = injury
addedInjury.userId = Auth.auth().currentUser?.uid
let _ = try db .collection("injuries").addDocument(from: addedInjury)
}
catch {
print(error)
}
}
func save () {
addInjury(injury: injury)
}
}
The selection and identifier of Picker have to be same type. Picker 的选择和标识符必须是相同的类型。 So you would have something like
所以你会有类似的东西
Picker(selection: $viewModel.injury.specificLocation, label: Text("General Location")) {
ForEach(locationOptions, id: \.self) {
Text($0)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.