你如何访问 &在 SwiftUI 2.0 中从多个其他视图编辑 @AppStorage 变量? [英] How do you access & edit an @AppStorage var from multiple other views in SwiftUI 2.0?
问题描述
有没有更好的方法来做到这一点?有没有办法访问环境中的UserDefaults??我做了以下事情:
Is there a better way to do this? Is there a way to access the UserDefaults in the environment?? I did the following:
struct ContentView: View {
@AppStorage("darkMode") var darkMode = false
var body: some View {
SubView(darkMode: $darkMode)
}
}
}
struct SubView: View {
@Binding var darkMode: Bool
var body: some View {
Text("Dark Mode is \(darkMode == true ? "on" : "off")")
}
}
推荐答案
通过在不同的视图中使用 @AppStorage
,您仍然可以访问相同的 UserDefaults.standard
存储(除非您明确指定suiteName
).
By using @AppStorage
in different views you still access the same UserDefaults.standard
storage (unless you explicitly specify the suiteName
).
这意味着您可以直接在子视图中使用 @AppStorage
.
Which means you can just use the @AppStorage
directly in the subview.
struct ContentView: View {
@AppStorage("darkMode") var darkMode = DefaultSettings.darkMode
var body: some View {
VStack {
Button("Toggle dark mode") {
self.darkMode.toggle()
}
SubView()
}
.colorScheme(darkMode ? .dark : .light)
.preferredColorScheme(darkMode ? .dark : .light)
}
}
struct SubView: View {
@AppStorage("darkMode") var darkMode = DefaultSettings.darkMode
var body: some View {
Text("Dark Mode is \(darkMode == true ? "on" : "off")")
}
}
enum DefaultSettings {
static let darkMode = false
}
注意:提取默认的 darkMode
值(到 DefaultSettings
枚举),因此您不会在每个视图中重复 false
.
Note: the default darkMode
value is extracted (to the DefaultSettings
enum) so you don't repeat false
in each view.
或者,您可以将 @AppStorage
直接注入 environment
.见:
Alternatively you can inject @AppStorage
directly to the environment
. See:
这篇关于你如何访问 &在 SwiftUI 2.0 中从多个其他视图编辑 @AppStorage 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!