テッド
テッド

Reputation: 906

Color Change Animation

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

Answers (1)

Hrabovskyi Oleksandr
Hrabovskyi Oleksandr

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

Related Questions