Reputation: 906
I'm trying to animate a color change on some text but I can't seem to get it to change gradually. I've tried both an implicit and explicit animation as seen in the code below, but no dice....
struct Example: View {
@State var showing = false
var body: some View {
VStack {
Text("test text").foregroundColor(showing ? .red : .blue)
.animation(.easeIn(duration: 2))
Button(action: toggle) {
Text("Toggle")
}
}
}
func toggle() {
withAnimation(.easeIn(duration: 2)) {self.showing.toggle()}
}
}
Can anyone give me some pointers?
Upvotes: 3
Views: 284
Reputation: 3275
Unfortunately, you can't animate .foregroundColor
. But you can animate .colorMultiply
. So in your case this will work:
struct ColorChangeAnimation: View {
@State private var multiplyColor: Color = .blue
var body: some View {
VStack {
Text("test text")
.foregroundColor(.white)
.colorMultiply(multiplyColor)
Button(action: toggle) {
Text("Toggle")
}
}
}
func toggle() {
withAnimation(.easeIn(duration: 2)) {
self.multiplyColor = (self.multiplyColor == .red) ? .blue : .red
}
}
}
Upvotes: 2