Issue #993
Before iOS 17, if you wanted to animate a number changing, SwiftUI would just fade the old number out and fade the new one in. It worked, but it wasn’t very exciting.
Here’s how that looked:
struct OldCounterView: View {
@State private var number = 0
var body: some View {
Text("\(count)")
.font(.largeTitle)
.onTapGesture {
withAnimation {
number += 1
}
}
}
}
When you tapped the text, the number would just disappear and reappear.
numbericText transition
Now, with just one extra line of code, you can make the numbers roll up or down to their new value. It looks much cooler and more professional.
Let’s use contentTransition(.numericText()) modifier.
Creates a content transition intended to be used with Text views displaying numeric text. In certain environments changes to the text will enable a nonstandard transition tailored to numeric characters that count up or down.
We can use to animate countsDown
whose default is false. For simple cases we can just use numericText()
To see it in action, let’s look at a fancier example. The code below creates a clean-looking counter with plus and minus buttons. When you tap them, the number animates beautifully.
You can find the code for this demo in FancyCounterView.swift
.
import SwiftUI
struct FancyCounterView: View {
@State private var count = 0
var body: some View {
ZStack {
Color(UIColor.systemGroupedBackground).ignoresSafeArea()
VStack(spacing: 30) {
Text("\(count)")
.font(.system(size: 90, weight: .bold, design: .rounded))
.contentTransition(.numericText())
HStack(spacing: 20) {
Button {
withAnimation(.spring) {
count -= 1
}
} label: {
Image(systemName: "minus.circle.fill")
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.red.opacity(0.8))
}
Button {
withAnimation(.spring) {
count += 1
}
} label: {
Image(systemName: "plus.circle.fill")
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.green.opacity(0.8))
}
}
}
.padding(40)
.background(.thinMaterial, in: RoundedRectangle(cornerRadius: 20))
}
}
}
Start the conversation