The countdown timer using Swift UI

Create 24-hour Countdown Timer using SwiftUI

A stepwise guide to create a 24-hour (24:00:00) countdown timer using SwiftUI

24-hour Timer format

Create a SwiftUI project

Create a project
Create a TimerView.swift

Prepare the UI

struct TimerView: View {
//MARK: - PROPERTIES
@State var timeRemaining = 24*60*60

//MARK: - BODY
var body: some View {

Text("\(timeString(time: timeRemaining))")
.font(.system(size: 60))
.frame(height: 80.0)
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(.white)
.background(Color.black)
}

//Convert the time into 24hr (24:00:00) format
func timeString(time: Int) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
}

Timer logic

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

Integrate Timer and View (Text)

.onReceive(timer){ _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}else{
self.timer.upstream.connect().cancel()
}
}

Complete Code

Countdown Timer — Live Preview

Bonus:

struct ContentView: View {
var body: some View {
VStack{
Text("Countdown Timer")
.font(.largeTitle)
.fontWeight(.semibold)
.padding(.vertical, 20.0)

TimerView()
}
.background(Color.orange)
.edgesIgnoringSafeArea(.all)
}
}
Embed Countdown Timer in ContentView

Source Code:

Consultant at GlobalLogic | iOS app developer | AWS Certified Solutions Architect - Associate

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store