Can @AppStorage be used in the Environment in SwiftUI?

2.5k views Asked by At

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

There are 1 answers

0
Mark On

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()
    }
}