gpt4 book ai didi

SwiftUI 如何临时为 View 颜色的foregroundColor 设置动画?

转载 作者:行者123 更新时间:2023-12-04 13:08:04 25 4
gpt4 key购买 nike

当按下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com