Skip to content

Instantly share code, notes, and snippets.

@scalbatty
Created February 14, 2023 10:25
Show Gist options
  • Save scalbatty/9a10cfbc71de156245ff04371aaebf07 to your computer and use it in GitHub Desktop.
Save scalbatty/9a10cfbc71de156245ff04371aaebf07 to your computer and use it in GitHub Desktop.
A "rolling counter" style label
struct AnimatedCounter: Animatable, View {
var value: CGFloat = 0
var maxOffset: CGFloat = 12
var animatableData: CGFloat {
get { value }
set { value = newValue }
}
var progress: CGFloat {
value - floor(value)
}
var body: some View {
ZStack {
if value.rounded() == value { // Integer, just show the text label
Text("\(Int(value))")
} else {
Text("\(Int(floor(value)))")
.offset(y: progress * -maxOffset)
.opacity(1.0 - progress)
Text("\(Int(ceil(value)))")
.offset(y: maxOffset + progress * -maxOffset)
.opacity(progress)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment