【问题标题】: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?当使用带有一系列选项的 swiftui 选择器时。如何将所选选项而不是索引值保存到 Cloud Firestore?
【发布时间】:2020-08-25 21:27:49
【问题描述】:

我希望能够访问和使用该位置。目前只有选择器中的索引值被保存到 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)
    }
    
}

【问题讨论】:

    标签: arrays firebase indexing google-cloud-firestore swiftui


    【解决方案1】:

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

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

    【讨论】:

    • 非常有帮助!非常感谢?
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多