Can @AppStorage be used in the Environment in SwiftUI?

柔情痞子 提交于 2021-01-28 05:00:46

问题


Can @AppStorage be used in the Environment in SwiftUI, if so, how would you do it?

I know you can send the value for the @AppStorage from one view to another using @Bindings as a general wondering I would like to know if its possible to put it in the environment. I don't have a practical example as to when this would be applicable, but I was wondering if it was possible.

Would this be crazy enough to work? I think you will only store the value and it won't be stored in the UserDefault.

struct RootView: View {
    @AppStorage("userPreferredDisplayMode") private var userPreferredDisplayMode: String = "automatic"
    @Environment(\.userPreferredDisplayMode) private var envUserPreferredDisplayMode: String    
    
    var body: some View {
        Text(title)
            .environment(\.userPreferredDisplayMode, envUserPreferredDisplayMode)
    }
}

回答1:


Turns out that you can.

struct CustomTextKey: EnvironmentKey {
    static var defaultValue: Binding<String> = Binding.constant("Default Text")
}

extension EnvironmentValues {
    var customText: Binding<String> {
        get { self[CustomTextKey.self] }
        set { self[CustomTextKey.self] = newValue }
    }
}

struct ContentView: View {
    @AppStorage("text") private var text: String = ""
    
    var body: some View {
        TextEditor(text: $text).padding()
        Divider()
        SecondView()
            .environment(\.customText, $text)
    }
}

struct SecondView: View {
    var body: some View {
        ThirdView()
    }
}
struct ThirdView: View {
    @Environment(\.customText) private var text: Binding<String>
    
    var body: some View {
        TextEditor(text: text).padding()
    }
}


来源:https://stackoverflow.com/questions/64252567/can-appstorage-be-used-in-the-environment-in-swiftui

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