[SwiftUI] Simple Countdown

Yoki
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 Combine
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

  1. 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.
  2. 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.
  3. 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!

--

--