首页 > 解决方案 > 如何将变量存储为 @AppStorage 变量的键

问题描述

所以我想在我的应用程序中切换到@AppStorage,但我遇到了一个特定问题。

对于@AppStorage 的键,我想使用我已经拥有的变量,但我不能这样做,但我曾经找到一种使用用户默认值的方法,如下所示。

 @State var isSignedUp = false

因此,我首先将 User Defaults 初始化为 @State var,然后在 .onAppear 中,我将使用密钥作为我的 id 变量:

isSignedUp = UserDefaults.standard.bool(forKey: id)

我要问的是如何使用@AppStorage 做到这一点?

标签: swiftswiftuiappstorage

解决方案


您可以分离id依赖的子视图并AppStorage动态初始化属性包装器。

这是一个解决方案。使用 Xcode 12.1 / iOS 14.1 测试

struct IsSignedView: View {

    @AppStorage var isSigned: Bool     // << declare

    init(id: String) {
        // Initialize with default value and dynamic key from argument
        self._isSigned = AppStorage(wrappedValue: false, id)
    }

    // ... other dependent code here
}

推荐阅读