Swift 如何将变量存储为@AppStorage变量的键
所以我想在我的应用程序中切换到@AppStorage,但我遇到了一个具体问题 对于@AppStorage的键,我想使用一个我已经拥有的变量,但我不能这样做,但我曾经找到一种使用用户默认值的方法,如下所示 因此,我首先将用户默认值初始化为@State变量,然后在.onAppear中使用key作为我的id变量: 我想问的是如何使用@AppStorage实现这一点 你可以试试Swift 如何将变量存储为@AppStorage变量的键,swift,swiftui,appstorage,Swift,Swiftui,Appstorage,所以我想在我的应用程序中切换到@AppStorage,但我遇到了一个具体问题 对于@AppStorage的键,我想使用一个我已经拥有的变量,但我不能这样做,但我曾经找到一种使用用户默认值的方法,如下所示 因此,我首先将用户默认值初始化为@State变量,然后在.onAppear中使用key作为我的id变量: 我想问的是如何使用@AppStorage实现这一点 你可以试试 @AppStorage("IsSigned") var isSigned = false 你可以试试 @
@AppStorage("IsSigned") var isSigned = false
你可以试试
@AppStorage("IsSigned") var isSigned = false
您可以分离
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
}
struct IsSignedView:视图{
@AppStorage var isSigned:Bool/您可以分离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
}
struct IsSignedView:视图{
@AppStorage var isSigned:Bool//不,我没有办法使用它,正如我说的,我需要在forEach中使用变量作为一个视图,其中有多个id,而不仅仅是一个我可以使用的id。不,我没有办法使用它,正如我说的,我需要在forEach中使用变量作为一个视图,其中有多个id,而不仅仅是一个我可以使用的id好的,我所做的就是使用了你的变量声明,然后在我之前的视图中,我展示了这个视图,以及我放在Appstorage中的变量(wrappedValue:false,id)它工作得很好!好吧,我所做的就是使用了你的变量声明,然后在我以前的视图中,我将视图及其变量放入Appstorage(wrappedValue:false,id)中,它工作得很好!