Animate text color in SwiftUI

In this tutorial, we will see how to animate a text color in SwiftUI.

We can animate the text color using the foregroundColor() modifier in various ways. Here are an example below to achieve text color animation.

We can use the withAnimation block to animate changes within its scope. We also need to use onTapGesture modifier to detect a tap on the text, and when tapped, the text color will change with a smooth animation.

.onTapGesture {
        withAnimation(.easeInOut(duration: 3)) {
            self.textColor = (self.textColor == .blue) ? .red : .blue
        }
    }

In the above code, I have used the onTapGesture modifier to detect a tap gesture on the text.

Then, Inside the onTapGesture closure, I have used withAnimation to make the color change of the text smooth and animated with easeInOut curve and a duration of 3 seconds.

Here is the complete code

import SwiftUI

struct ContentView: View {
    // State variable to hold the text color, initially set to blue
    @State private var textColor: Color = .blue

    var body: some View {
        Text("Hello, SwiftUI!")
            .font(.largeTitle)
            .foregroundColor(.white)
            // Multiply the color of the text by the specified color (self.textColor)
            .colorMultiply(self.textColor)
            .onTapGesture {
                // Animate the color change with easeInOut animation over a duration of 3 seconds
                withAnimation(.easeInOut(duration: 3)) {
                    // Toggle the text color between blue and red when tapped
                    self.textColor = (self.textColor == .blue) ? .red : .blue
                }
            }
    }
}

When we tap the text, the textColor will toggle between blue and red. The withAnimation block ensures that the change is animated.

Output:

Animate text color in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *