繁体   English   中英

使用带有一系列选项的 swiftui 选择器时。 如何将所选选项而不是索引值保存到 Cloud Firestore?

[英]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?

我希望能够访问和使用该位置。 目前只有选择器的索引值被保存到 Cloud Firestore。

这是选择器:

Picker(selection: $viewModel.injury.locationIndex, label: Text("General Location")) {
  ForEach(0 ..< locationOptions.count) {
    Text(self.locationOptions[$0])
}

这是数组:

var locationOptions = ["🤕 Head", "🦺 Chest", "💪 Right Arm", "💪 Left Arm", "🤚 Right Hand", "✋ Left Hand", "🩲 Waist", "🦵 Right Leg", "🦵 Left Leg", "🦶 Right Foot", "🦶 Left Foot"]

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

Picker 的选择和标识符必须是相同的类型。 所以你会有类似的东西

Picker(selection: $viewModel.injury.specificLocation, label: Text("General Location")) {
  ForEach(locationOptions, id: \.self) {
    Text($0)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM