O @AppStorage pode ser usado no ambiente no SwiftUI?

Oct 08 2020

O @AppStorage pode ser usado no ambiente no SwiftUI, em caso afirmativo, como você faria isso?

Eu sei que você pode enviar o valor do @AppStorage de uma view para outra usando o @Bindings como uma dúvida geral, gostaria de saber se é possível colocá-lo no ambiente. Não tenho um exemplo prático de quando isso seria aplicável, mas queria saber se seria possível.

Isso seria louco o suficiente para funcionar? Acho que você só vai armazenar o valor e ele não será armazenado no 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)
    }
}

Respostas

2 Mark Oct 08 2020 at 07:30

Acontece que você pode.

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