Animating number changes in SwiftUI
Table of Contents
iOS 17 bring a new and beautiful way to animate number in SwiftUI. Let's learn how to do it.
Before iOS 17, if you tried to animate a number in SwiftUI, you would get a simple fade in/out animation.
struct ContentView: View {
@State private var number: Int = 0
var body: some View {
VStack(spacing: 20) {
Text("\(number)")
Button {
withAnimation {
number = .random(in: 0 ..< 200)
}
} label: {
Text("Random")
}
}
.font(.largeTitle)
}
}
This is what you will get: a fade animation.
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
How to animate number changes in iOS 17
In iOS 17, SwiftUI has a built-in way to animate numbers.
This is what it looks like.
To animate the number in iOS 17, we apply .contentTransition(.numericText())
to a text view.
struct ContentView: View {
@State private var number: Int = 0
var body: some View {
VStack(spacing: 20) {
// 1
Text("\(number)")
.contentTransition(.numericText())
Button {
withAnimation {
number = .random(in: 0 ..< 200)
}
} label: {
Text("Random")
}
}
.font(.largeTitle)
}
}
1 The only thing we need to do to enjoy this beautiful animation is to use the .contentTransition
modifier with the numericText()
transition.
Read more article about SwiftUI or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to create custom view modifiers in SwiftUI
Learn how to create reuse styles using ViewModifier.