Animating number changes in SwiftUI

⋅ 1 min read ⋅ 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.

Animating number change in iOS 16.
Animating number change in iOS 16.

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

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.

Animating number change in iOS 17.
Animating number change in iOS 17.

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 Share
Previous
How to create custom view modifiers in SwiftUI

Learn how to create reuse styles using ViewModifier.

Next
Black Friday Deal 2024

This is my first year doing a Black Friday deal.

← Home