可以在SwiftUI的环境中使用@AppStorage吗? [英] Can @AppStorage be used in the Environment in SwiftUI?

查看:155
本文介绍了可以在SwiftUI的环境中使用@AppStorage吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@AppStorage是否可以在SwiftUI的环境中使用,如果可以,您将如何使用它?

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

我知道您可以使用@Bindings将@AppStorage的值从一个视图发送到另一个视图,这是一个普遍的问题,我想知道是否有可能将其放入环境中.对于何时适用,我没有实际的例子,但我想知道是否有可能.

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.

这足以使工作疯狂吗?我认为您只会存储该值,而不会存储在UserDefault中.

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

推荐答案

事实证明您可以.

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

这篇关于可以在SwiftUI的环境中使用@AppStorage吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆