[英]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.