Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color Change Animation

Tags:

swiftui

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?

like image 366
テッド Avatar asked Dec 11 '25 22:12

テッド


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
        }
    }
}
like image 69
Hrabovskyi Oleksandr Avatar answered Dec 13 '25 15:12

Hrabovskyi Oleksandr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!