当按下 View 时,我通过模型知道 button.isSelected
.如何为 View 的前景色设置动画,类似于 IOS 计算器按钮按下动画?
就像是:
白色 -> 灰色 -> 白色
struct ButtonView: View {
let button: ViewModel.Button
var body: some View {
let shape = Rectangle()
ZStack {
shape.fill().foregroundColor(button.isSelected ? Color.gray : Color.white)
.animation(Animation.linear(duration: 0.01))
.border(Color.black, width: 0.33)
Text(button.content)
.font(Font.system(size:32))
}
}
}
最佳答案
我认为有很多方法可以做到这一点。
其中,我会用DispatchQueue.main.asyncAfter()
写一个例子
struct ContentView: View {
@State private var isSelected: Bool = false
var body: some View {
VStack {
Button {
isSelected = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2 ) {
// To change the time, change 0.2 seconds above
isSelected = false
}
} label: {
Text("Button")
.foregroundColor(isSelected ? Color.red : Color.blue)
}
}
}
}
关于SwiftUI 如何临时为 View 颜色的foregroundColor 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68448273/