简体   繁体   English

SwiftUI 中的状态变量未选取 UserDefaults .set

[英]UserDefaults .set not being picked up by state variable in SwiftUI

I am attempting to to detect whether a user has onboarded or not eg launched the app.我试图检测用户是否已加入,例如启动应用程序。 When I access the UserDefaults.standard.bool directly I can see the change but when I attempt to access it through the @State it retains the original false value.当我直接访问UserDefaults.standard.bool ,我可以看到更改,但是当我尝试通过@State访问它时,它保留了原始的false值。

As a workaround I directly change the value to true , but I have a feeling this isn't the way to do this.作为一种解决方法,我直接将值更改为true ,但我感觉这不是这样做的方法。

How can I get the @State variable to pick up the change when changing the UserDefaults object without having to close and restart the app?在更改UserDefaults对象时如何让@State变量获取更改而无需关闭并重新启动应用程序? I want the user to onboard, click a button, then switch immediately to the main app view.我希望用户加入,单击一个按钮,然后立即切换到主应用程序视图。

@State var userOnboarded: Bool = UserDefaults.standard.bool(forKey: "userOnboarded")
    
    var body: some Scene {
        WindowGroup {
            if userOnboarded {
                Text("PLACEHOLDER: Main App View")
            } else {
                Button(action: {
                    UserDefaults.standard.set(true, forKey: "userOnboarded")
                    userOnboarded = true
                    print(UserDefaults.standard.bool(forKey: "userOnboarded"))
                }) {
                    VStack {
                        Text("Click circle to onboard.")
                        Circle()
                            .foregroundColor(Color.red)
                    }
                }
            }
        }

In SwiftUI there is a dedicated wrapper to watch UserDefaults.在 SwiftUI 中有一个专门的包装器来观察 UserDefaults。 As previously mentioned in your comments, it's called @AppStorage and it's used like so.正如您之前在评论中提到的,它被称为@AppStorage ,它的使用方式是这样的。

@AppStorage("userOnboarded") var userOnboarded: Bool = false

It functions similarly to a UserDefault but will refresh the view and set the data when the value changes.它的功能类似于 UserDefault,但会在值更改时刷新视图并设置数据。

Button(action: {
    userOnboarded = true
    print(UserDefaults.standard.bool(forKey: "userOnboarded"))
}) //....

Notice in the button, we set the userOnboarded to true, this will update and refresh your view as well as update the user default value.注意在按钮中,我们将 userOnboarded 设置为 true,这将更新和刷新您的视图以及更新用户默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM