[英]SwiftUI change and animate foreground color
I'm new to swiftUI and I am trying to I have a blue view flash green for half a second and then go back to blue.我是 swiftUI 的新手,我正在尝试将蓝色视图 flash 显示为绿色半秒钟,然后将 go 恢复为蓝色。 I've tried multiple ways.
我尝试了多种方法。 I have tried setting the color to a state variable but that does not work.
我尝试将颜色设置为 state 变量,但这不起作用。 In the current code below the view just remains blue.
在下面的当前代码中,视图只是保持蓝色。 Current implementation
当前实施
You can do it with State Variable您可以使用 State 变量来做到这一点
@State private var color = Color.red
var body: some View {
Circle()
.aspectRatio(contentMode: .fit)
.foregroundColor(color)
.onAppear {
withAnimation(.easeInOut(duration: 4)) {
self.color = Color.blue
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
withAnimation(.easeInOut(duration: 4)){self.color = Color.red }
}
}
}
I wrote this out but it seems to be skipping over the first animation.我写了这个,但它似乎跳过了第一个 animation。
@State private var color = Color.blue
var body: some View {
Circle()
.aspectRatio(contentMode: .fit)
.foregroundColor(color)
.onAppear {
withAnimation(.easeInOut(duration: 2)) {
self.color = Color.green
}
withAnimation(
Animation.easeInOut(duration: 2)
.delay(2)
) {
self.color = Color.blue
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.