How to animate/transition text value change in SwiftUI
I couldn't find a way to animate the text value with a fade. When setting the animation property of a Text
you will see three dots (...) when animating.
As for now I figured out a work around which will change the opacity:
@State private var textValue: Int = 1
@State private var opacity: Double = 1
var body: some View {
VStack (spacing: 50) {
Text("\(textValue)")
.font(.largeTitle)
.frame(width: 200, height: 200)
.opacity(opacity)
Button("Next") {
withAnimation(.easeInOut(duration: 0.5), {
self.opacity = 0
})
self.textValue += 1
withAnimation(.easeInOut(duration: 1), {
self.opacity = 1
})
}
}
}
This will fade out and fade in the text when you change it.
So it turns out this is really easy
Text(textValue)
.font(.largeTitle)
.frame(width: 200, height: 200)
.transition(.opacity)
.id("MyTitleComponent" + textValue)
Note the additional id
at the end. SwiftUI uses this to decide if it's dealing with the same view or not when doing a redraw. If the id is different then it assumes the previous view was removed and this one has been added. Because it's adding a new view it applies the specified transition as expected.
NB: It's quite possible that this id should be unique for the entire view tree so you probably want to take care to namespace it accordingly (hence the MyTitleComponent
prefix in the example).