我会推荐什么:ObservableObject
called UserSettings
。然后,您可以从应用程序场景或 @main 所在的位置将其注入到整个应用程序中.environmentObject(UserSettings(...))
.
对于需要访问实例的视图UserSettings
,您将执行以下操作:
@EnvironmentObject private var userSettings: UserSettings
Example
环境对象:
class UserSettings: ObservableObject {
enum Sex: String {
case male
case female
case other
}
@Published var sex: Sex
@Published var weight: Double
@Published var license: Bool
init(sex: Sex, weight: Double, license: Bool) {
self.sex = sex
self.weight = weight
self.license = license
}
}
@main
struct WhateverThisIsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(UserSettings(sex: .male, weight: 100, license: true))
}
}
}
Views:
struct ContentView: View {
@EnvironmentObject private var userSettings: UserSettings
var body: some View {
VStack {
Text("Current settings:")
Text("Sex: \(userSettings.sex.rawValue)")
Text("Weight: \(userSettings.weight)")
Text("License: \(userSettings.license ? "yes" : "no")")
SomeChildView()
}
}
}
struct SomeChildView: View {
@EnvironmentObject private var userSettings: UserSettings
var body: some View {
Picker("Sex", selection: $userSettings.sex) {
Text("Male").tag(UserSettings.Sex.male)
Text("Female").tag(UserSettings.Sex.female)
Text("Other").tag(UserSettings.Sex.other)
}
.pickerStyle(.segmented)
}
}
Result:
有关使用环境对象的完整演示,请参阅我的答案here https://stackoverflow.com/a/59919052/9607863以及相关的存储库。