简体   繁体   English

存储来自选择器的选定值以在其他视图中使用 - SwiftUI

[英]Storing a selected value from picker to use in other views - SwiftUI

I was very kindly helped to allow my picker to select a value from my Firestore database.我得到了非常友好的帮助,允许我的选择器从我的 Firestore 数据库中选择一个值。 What I would like to do is once that value is selected in my picker I would like to be able to show that value in other views.我想做的是一旦在我的选择器中选择了该值,我希望能够在其他视图中显示该值。 I have tried setting this up using UserDefaults but I'm not sure that's the way to go?我试过使用 UserDefaults 进行设置,但我不确定这是要走的路吗? If you could suggest a better method I'd be more than grateful.如果您能提出更好的方法,我将不胜感激。 My code currently is below.我的代码目前在下面。

The value in the below code returns Unknown School each time but without the user defaults works flawlessly in fetching the data.下面代码中的值每次都返回 Unknown School 但没有用户默认值在获取数据时完美无缺。

Thanks in advance.提前致谢。

import SwiftUI
import Firebase

struct SchoolDetailsView: View {
    @ObservedObject var schoolData = getSchoolData()
    @State private var selectedSchool = UserDefaults.standard.string(forKey: "") // `schoolName.id` is of type String

    var body: some View {
        VStack {
                Form {
                    Section {
                        Picker(selection: $selectedSchool, label: Text("School Name")) {
                            ForEach(schoolData.datas, id: \.id) {
                                Text($0.name)
                            }
                        }
                        Text("Selected School: \(selectedSchool ?? "Unknown School")")
                    }
                }.navigationBarTitle("School Selection")
            }
        }

struct SchoolPicker_Previews: PreviewProvider {
    static var previews: some View {
        SchoolDetailsView()
    }
}

class getSchoolData : ObservableObject{
    
    @Published var datas = [schoolName]()
    
    init() {
        
        let db = Firestore.firestore()
        
        db.collection("School Name").addSnapshotListener { (snap, err) in
            
            if err != nil{
                
                print((err?.localizedDescription)!)
                return
            }
            
            for i in snap!.documentChanges{
                
                let id = i.document.documentID
                let name = i.document.get("Name") as! String
                
                self.datas.append(schoolName(id: id, name: name))
            }
        }
    }
}

struct schoolName : Identifiable {
    
    var id : String
    var name : String
}
}

First, the UserDefaults key for your variable can't be empty:首先,变量的 UserDefaults 键不能为空:

@State private var selectedSchool: String = UserDefaults.standard.string(forKey: "selectedSchool") ?? "Unknown School"

Then you can use onReceive to update the variable:然后你可以使用onReceive来更新变量:

.onReceive(Just(selectedSchool)) {
    UserDefaults.standard.set($0, forKey: "selectedSchool")
}

Full code:完整代码:

import Combine
import Firebase
import SwiftUI

struct SchoolDetailsView: View {
    @ObservedObject var schoolData = getSchoolData()
    @State private var selectedSchool = UserDefaults.standard.string(forKey: "selectedSchool")

    var body: some View {
        VStack {
            Form {
                Section {
                    Picker(selection: $selectedSchool, label: Text("School Name")) {
                        ForEach(schoolData.datas, id: \.id) {
                            Text($0.name)
                        }
                    }
                    .onReceive(Just(selectedSchool)) {
                        UserDefaults.standard.set($0, forKey: "selectedSchool")
                    }
                    Text("Selected School: \(selectedSchool)")
                }
            }.navigationBarTitle("School Selection")
        }
    }
}

Note that in SwiftUI 2 / iOS 14 you can use @AppStorage instead.请注意,在SwiftUI 2 / iOS 14 中,您可以改用@AppStorage

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

相关问题 使用带有一系列选项的 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? swiftUI 中的选择器正在从 Firestore 中选择文档 ID 而不是文档字段 - Picker in swiftUI is selecting document ID instead of document field from Firestore 带有 Cloud Firestore 的 SwiftUI 选择器 - SwiftUI Picker with Cloud Firestore SwiftUI 和 Picker 和 FireStore 返回文档 ID 不下降 - SwiftUI and Picker and FireStore return doc ID not fall 在属性 SwiftUI 中存储 Firebase 侦听器有什么好处? - What are the benefits of storing a Firebase listener in a property SwiftUI? Initializer 'init(_:)' 要求 '' 符合 'StringProtocol' SwiftUI Picker with Firebase - Initializer 'init(_:)' requires that '' conform to 'StringProtocol' SwiftUI Picker with Firebase Swift 用户默认不存储值 - Swift userdefaults not storing value SwiftUI 列出重复 ID 值 - SwiftUI List Repeating ID Value 如何将所选值从 select 获取到另一个组件? - How do I get the selected value from the select to another component? 如何在 SwiftUI 的不同视图中更新 Cloud Firestore 中的数据? - How to update data in Cloud Firestore in different views for SwiftUI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM