Reputation: 727
I'm really new to Swift and iOS apps and couldn't figure the following out.
I'm trying to create a simple 5 steps rating element storing a value to the user defaults. It works however not "on the fly" meaning the user can't see the change instantly but only on relaunching the app. The rating indicated through different opacities.
So, the problem is: The changes are not shown instantly on tapping but only after relaunching the app.
I read articles about @AppStorage but couldn't figure it out.
struct EverythingView: View {
@AppStorage("customRating") var customTemp: Int = 1
HStack (spacing: 6) {
ForEach(1...5, id: \.self) { index in
Circle()
.fill(Color(.green))
.frame(width: 15, height: 15)
.onTapGesture {
customRating = index
print(customRating) // prints the correct value on the fly
}
.opacity(index > customRating ? 0.5 : 1) // does not update the opacity of the circles on the fly, only on relaunching the app
}
}
}
Do I have to access @AppStorage again somewhere inside the loop? From what I understood it updates and propagates itself automatically?
Thanks for any tips!
EDIT:
Using an @State
instead of @AppStorage
var
works as expected.
Upvotes: 1
Views: 2159
Reputation: 1294
you're doing it right you just have a typo in your first line. your @AppStorage property also needs to be named customRating
struct EverythingView: View {
@AppStorage("customRating") var customRating: Int = 1 //<---property name should be customRating
var body: some View {
Color.clear
HStack (spacing: 6) {
ForEach(1...5, id: \.self) { index in
Circle()
.fill(Color(.green))
.frame(width: 15, height: 15)
.onTapGesture {
customRating = index
print(customRating) // prints the correct value on the fly
}
.opacity(index > customRating ? 0.5 : 1) // does not update the opacity of the circles on the fly, only on relaunching the app
}
}
}
}
Upvotes: 1