Color Change Animation

Viewed 186

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?

1 Answers

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
        }
    }
}
Related