How do you access & edit an @AppStorage var from multiple other views in SwiftUI 2.0?

风流意气都作罢 提交于 2020-12-15 06:23:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!