I am trying to animate value change in a text using withAnimation
but it doesn't seem to work. I have come across a similar question but the answer is not animating the text value.
I am trying to recreate this behaviour in pure SwiftUI (UIKit Example):
I have tried this code but it doesn't animate the text change:
struct TextAnimationView: View {
@State private var textValue = "0"
var body: some View {
VStack (spacing: 50) {
Text(textValue)
.font(.largeTitle)
.frame(width: 200, height: 200)
.transition(.opacity)
Button("Next") {
withAnimation (.easeInOut(duration: 1)) {
self.textValue = "\(Int.random(in: 1...100))"
}
}
}
}
}
I have a very little experience with SwiftUI, is there another way to achieve this?
Thanks in advance :)
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).