简体   繁体   English

SwiftUI 将 EnvironmentObject 传递给 class

[英]SwiftUI Pass EnvironmentObject to a class

I'm struggling with passing an variable to a class.我正在努力将变量传递给 class。

I have a class with different settings I store.我有一个 class,我存储了不同的设置。 The data is available and might be changed on different views.数据可用,并且可能会在不同的视图中更改。

class UserData: ObservableObject {
    @Published var ZipCode = "DK6700"   
}

The class is on my main view initialised as StateObject: class 在我的主视图中初始化为 StateObject:

struct ContentView: View {
    @StateObject var SavedData = UserData()

    var body: some View {
        NavigationView {
        ChartView()
        }
        .edgesIgnoringSafeArea(.bottom)
        .environmentObject(SavedData)
    }
}

I call the Struct ChartView() where UserData is initialised as我将 UserData 初始化为的 Struct ChartView() 称为

@EnvironmentObject var SavedData: UserData
@ObservedObject var dataModel = DataModel()

and from the corresponding View, i can access the stored ZipCode.从相应的视图中,我可以访问存储的邮政编码。 So far so good.到目前为止,一切都很好。 The ChartView calls another class, where I download data in JSON format. ChartView 调用另一个 class,我在这里下载 JSON 格式的数据。 This works as well, but I need the stored ZIP code in this class, and I can't figure out how to pass it.这也有效,但我需要这个 class 中存储的 ZIP 代码,但我不知道如何传递它。 Currently ZIP is hardcoded in the DataModel, and works, but it should be the stored value instead.目前 ZIP 在数据模型中是硬编码的,并且有效,但它应该是存储的值。

My DataModel() :我的DataModel()

class DataModel: ObservableObject {
    @EnvironmentObject var SavedData: UserData
    @MainActor @Published var Data: [MyData] = []
    var ZIP:String = "3000"

    @MainActor func reload() async {
        let url = URL(string: "https://MyURL?zip=\(ZIP)")!
        let urlSession = URLSession.shared

        do {
            ...
        } catch {
            ...
        }
    }   
}

Any suggestions to get the stored ZIP code to my DataModel Class?将存储的 ZIP 代码获取到我的DataModel Class 有什么建议吗?

How about changing your function signature to将您的 function 签名更改为

@MainActor func reload(for zipCode: String) async {

and passing it in when you call the function?并在您拨打 function 时传递它?

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

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