Home > Net >  Save the value of the pressed button (SwiftUI)
Save the value of the pressed button (SwiftUI)

Time:01-18

How to save the value of the pressed button and its color, if the user clicks on the button, it will turn red when the user restarts the application, the color of the button will remain and be red, and the same with gray. I know that for something like this you need to use AppStorage or UserDefaults, but I haven't found how to use it in my case.

Сode:

struct HeartButtonView: View {
    @State private var isLiked = false
    var body: some View {
        HeartButton(isLiked: $isLiked)
    }
}


struct HeartButton: View {
    
    @Binding var isLiked: Bool
    @State private var animate = false
    private let animationDuration: Double = 0.1
    private var animationScale: CGFloat {
        isLiked ? 0.7 : 1.3
    }
    
    var body: some View {
        
        Button {
            self.animate = true
            DispatchQueue.main.asyncAfter(deadline: .now()   self.animationDuration) {
                self.animate = false
                self.isLiked.toggle()
            }
        } label: {
            Image(systemName: isLiked ? "heart.fill" : "heart")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 50)
                .foregroundColor(isLiked ? .red : .gray)
        }
        .scaleEffect(animate ? animationScale : 1)
        .animation(.easeIn(duration: animationDuration), value: animate)
        
    }
}

Thanks for any solution

CodePudding user response:

To use AppStorage to store the state of this button, it's just a case of replacing

@State private var isLiked = false

with

@AppStorage("isLiked") private var isLiked = false

e.g

struct HeartButtonView: View {
    @AppStorage("isLiked") private var isLiked = false
    var body: some View {
        HeartButton(isLiked: $isLiked)
    }
}

The button state will be persisted between runs of the app

  • Related