I am really stuck on this. I want to make several button, each having independet state of ifButtonDisabled. The button disables when user clicks on it. Since, I want my app to remember the state of the button when the app reloads or refresh, I am using AppStorage. The problem is since each button has independent state, AppStorage variable should also be different. But since self is not avaialble, I am not able to have a dnamic name for my AppStorage variable.
Also, Is there any better alternative to achieve the same functionality???
struct ButtonData {
var id: UUID {
return UUID()
}
let level: String
let bgColor: String
let image: String
@AppStorage(level) var ifDisabled: Bool = false
}
I'm not sure why you would want to have an
idthat changes every time you access it, but if you just want to initialiseisDisabled, you can write your owninit, and assign anAppStorageto_isDisabledthere.That said, your view won't update if you want to use it like this:
Because
AppStoragehas anonmutatingsetter, so setting it won't causebuttonDatain the view to mutate, and so SwiftUI doesn't know that your view needs updating.So if you want
AppStorageto update views, you need to put it directly in aView. For example, you could make your own button view that takes in aButtonData, and sets its disabled status accordingly:Now whenever the superview updates the
AppStorage,MyButtonwill update its disabled status too.