pet*_*erk 5 swift swiftui appstorage
所以我想在我的应用程序中切换到@AppStorage,但我遇到了一个特定问题。
对于 @AppStorage 的键,我想使用一个我已经拥有的变量,但我不能这样做,但我曾经找到一种使用用户默认值来做到这一点的方法,如下所示。
@State var isSignedUp = false
Run Code Online (Sandbox Code Playgroud)
因此,我首先将用户默认值初始化为 @State var,然后在 .onAppear 中,我将使用该密钥作为我的 id 变量:
isSignedUp = UserDefaults.standard.bool(forKey: id)
Run Code Online (Sandbox Code Playgroud)
我要问的是如何使用@AppStorage 做到这一点?
Asp*_*eri 10
您可以分离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
}
Run Code Online (Sandbox Code Playgroud)