保存按下按钮的值(SwiftUI)

sqserrrh  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(153)

如何保存按下按钮的值及其颜色,如果用户点击按钮,当用户重新启动应用程序时,按钮将变为红色,按钮的颜色将保持红色,灰色也是如此。我知道,对于这样的东西,你需要使用AppStorage或UserDefaults,但我还没有找到如何在我的情况下使用它。

国家代码:

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)
        
    }
}

谢谢你的任何解决办法

mnemlml8

mnemlml81#

要使用AppStorage存储此按钮的状态,只需将

@State private var isLiked = false

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

例如

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

按钮状态将在应用程序运行之间保持不变

相关问题