问题
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")")
}
}
回答1:
By using @AppStorage in different views you still access the same UserDefaults.standard storage (unless you explicitly specify the suiteName).
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
}
Note: the default darkMode value is extracted (to the DefaultSettings enum) so you don't repeat false in each view.
Alternatively you can inject @AppStorage directly to the environment. See:
- Can @AppStorage be used in the Environment in SwiftUI?
来源:https://stackoverflow.com/questions/64117138/how-do-you-access-edit-an-appstorage-var-from-multiple-other-views-in-swiftui