[SwiftUI] Simple Countdown
1 min readSep 2, 2024
In a workout app, it’s common to display a countdown timer at the start of a workout to prepare the user. Let’s create this countdown using SwiftUI.
Code
Here’s how you can implement the countdown in SwiftUI:
import CombineGet Yoki’s stories in your inbox
Join Medium for free to get updates from this writer.
import SwiftUI
struct CountDownView: View {
@State private var timeRemaining = 5
@State private var scale: CGFloat = 1.0
@State private var opacity: CGFloat = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Text("\(timeRemaining)")
.font(.system(size: 100))
.scaleEffect(scale)
.opacity(opacity)
.onReceive(timer) { _ in
if timeRemaining > 0 {
withAnimation(.bouncy(duration: 0.3)) {
scale = 3
opacity = 1
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
scale = 1
opacity = 0.0
timeRemaining -= 1
}
if timeRemaining == 0 {
timer.upstream.connect().cancel()
}
}
}
}
}
#Preview {
CountDownView()
}
How It Works
- Timer Setup:
I use Timer.publish(every: 1, on: .main, in: .common).autoconnect() to create a timer that fires every second and automatically starts when the view appears. - Animation:
withAnimation(.bouncy(duration: 0.3)) animates the number by increasing its size and making it visible.
After 0.6 seconds, set the next number. - Countdown Logic:
The timeRemaining variable controls the countdown. When it reaches 0, the timer stops to prevent further updates.
I hope this will be helpful to you!

![[SwiftUI] Swipeable Card Stack](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*PfeFetHs2KISsfRLID_Mvw.gif)





