swift - 如何将变量存储为 @AppStorage 变量的键
问题描述
所以我想在我的应用程序中切换到@AppStorage,但我遇到了一个特定问题。
对于@AppStorage 的键,我想使用我已经拥有的变量,但我不能这样做,但我曾经找到一种使用用户默认值的方法,如下所示。
@State var isSignedUp = false
因此,我首先将 User Defaults 初始化为 @State var,然后在 .onAppear 中,我将使用密钥作为我的 id 变量:
isSignedUp = UserDefaults.standard.bool(forKey: id)
我要问的是如何使用@AppStorage 做到这一点?
解决方案
您可以分离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
}
推荐阅读
- java - 如何使用非对称加密在另一个应用程序中解密来自一个应用程序的文本?
- xamarin - Xamarin Forms ListView 取消 ItemSelected 事件
- firebase - Vuejs 和 Firebase 存储问题。未捕获的类型错误:存储不是函数
- php - 将可点击的电话号码添加到 php 邮件
- asp.net-core - 使用 VS2019 和 ASP.NET 核心通过 SSH 附加到进程不起作用
- r - 在 R 中拆分()之后保持数据的原始顺序
- javascript - 为通过 window.open() 打开的外部页面应用 CSS
- html - 粘性侧边栏在 Firefox 中没有正确的顶部空间
- c# - 鉴于一台服务器上的 ASP.Net MVC 站点但另一台服务器上的 ASP.Net MVC 站点,HttpContext.Current.User.Identity 为空/空
- python - 芹菜任务的 finally 子句不执行,我该如何清理?