SwiftUI,如何使背景颜色多次动画化 [英] SwiftUI, how to make the background color animate multiple times
问题描述
我有一个 SwiftUI 项目,其中包含一个带有 .onTapGesture 的 Text 对象,该对象在触发时应使按钮的背景颜色弹出为另一种颜色,然后快速淡入原始颜色.在我的代码中,我能够触发颜色弹出,但它会保持这种状态并且不会消失.我有点不知所措,任何帮助表示赞赏......这是我正在使用的代码:
I have a SwiftUI project that includes a Text object with a .onTapGesture working that, when triggered, should cause the button's background color to pop to another color then quickly fade back to the original color. In my code, I'm able to trigger the color pop, but it stays that way and won't fade back. I'm kind of at a loss on what to do, any help is appreciated...here is the code I'm using:
@State var buttonFlash = false
var body: some View {
Text("Hello")
.font(.system(size: 20))
.frame(width: 30, height: 30)
.foregroundColor(Color.blue)
.background(buttonFlash ? Color.white : Color.red)
.animation(nil)
.background(Color.red)
.animation((Animation.linear).delay(0.1))
.cornerRadius(30)
.onTapGesture {
print("Tapped!")
self.buttonFlash.toggle()
}
推荐答案
应该使按钮的背景颜色弹出为另一种颜色,然后快速淡入原始颜色.
should cause the button's background color to pop to another color then quickly fade back to the original color.
您需要为此声明一个函数.这是一种可能的方法:
You need to declare a function for that. Here is a possible approach for it:
struct ContentView: View {
@State var buttonFlash: Bool = false
var body: some View {
Text("Hello")
.font(.system(size: 20))
.frame(width: 100, height: 50)
.foregroundColor(Color.blue)
.background(buttonFlash ? Color.white : Color.red)
.cornerRadius(30)
.onTapGesture {
print("Tapped!")
self.colorChange()
}
}
private func colorChange() {
// first toggle makes it red
self.buttonFlash.toggle()
// wait for 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
// Back to normal with ease animation
withAnimation(.easeIn){
self.buttonFlash.toggle()
}
})
}
}
一旦点击它就会调用该方法.然后触发颜色变化并在 1 秒后反转.
It calls the method once tapped. This then triggers the color change and reverses it after 1 second.
产生这个结果:
这篇关于SwiftUI,如何使背景颜色多次动画化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!