首页 > 解决方案 > 当使用带有一系列选项的 swiftui 选择器时。如何将所选选项而不是索引值保存到 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)
    }
    
}

标签: arraysfirebaseindexinggoogle-cloud-firestoreswiftui

解决方案


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

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

推荐阅读