Search code examples
iosswiftswiftui

SwiftUI: Animate Text color - foregroundColor()


I've been trying to work on animating various parts of the UI, but it seems as though you can't animate a SwiftUI Text's foregroundColor? I want to switch the color of some text smoothly when a state changes. This works fine if I animate the background color of the Text's surrounding view, but foreground color does not work. Has anyone had any luck animating a change like this? Unsure if this is an Xcode beta bug or it's intended functionality...

Text(highlightedText)
    .foregroundColor(color.wrappedValue)
    .animation(.easeInOut)

// Error: Cannot convert value of type 'Text' to closure result type '_'

Solution

  • There is a much easier way, borrowing from Apple's "Animating Views and Transitions" tutorial code. The instantiation of GraphCapsule in HikeGraph demonstrates this.

    While foregroundColor cannot be animated, colorMultiply can. Set the foreground color to white and use colorMultiply to set the actual color you want. To animate from red to blue:

    struct AnimateDemo: View {
        @State private var color = Color.red
    
        var body: some View {
            Text("Animate Me!")
                .foregroundColor(Color.white)
                .colorMultiply(self.color)
                .onTapGesture {
                    withAnimation(.easeInOut(duration: 1)) {
                        self.color = Color.blue
                    }
            }
        }
    }
    
    struct AnimateDemo_Previews: PreviewProvider {
        static var previews: some View {
            AnimateDemo()
        }
    }