繁体   English   中英

保存按下按钮的值(SwiftUI)

[英]Save the value of the pressed button (SwiftUI)

如何保存按下按钮的值及其颜色,如果用户点击按钮,当用户重新启动应用程序时它会变成红色,按钮的颜色将保持为红色,与灰色相同。 我知道对于这样的事情你需要使用 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)
        
    }
}

感谢任何解决方案

要使用AppStorage来存储这个按钮的state,只是替换一个例子

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

按钮 state 将在应用程序运行之间保留

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM