简体   繁体   English

保存按下按钮的值(SwiftUI)

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

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.我知道对于这样的事情你需要使用 AppStorage 或 UserDefaults,但我还没有找到如何在我的案例中使用它。

С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感谢任何解决方案

To use AppStorage to store the state of this button, it's just a case of replacing要使用AppStorage来存储这个按钮的state,只是替换一个例子

@State private var isLiked = false

with

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

eg例如

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按钮 state 将在应用程序运行之间保留

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

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