Skip to main content

How to use a timer with SwiftUI

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to use a timer with SwiftUI 관련

SwiftUI by Example

Back to Home

How to use a timer with SwiftUI | SwiftUI by Example

How to use a timer with SwiftUI

Updated for Xcode 15

If you want to run some code regularly, perhaps to make a countdown timer or similar, you should use Timer and the onReceive() modifier.

For example, this code creates a timer publisher that fires every second, updating a label with the current time:

struct ContentView: View {
    @State private var currentDate = Date.now
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(currentDate)")
            .onReceive(timer) { input in
                currentDate = input
            }
    }
}

Download this as an Xcode projectopen in new window

It's important to use .main for the runloop option, because our timer will update the user interface. As for the .common mode, that allows the timer to run alongside other common events – for example, if the text was in a scroll view that was moving.

As you can see, the onReceive() closure gets passed in some input containing the current date. In the code above we assign that straight to currentDate, but you could use it to calculate how much time has passed since a previous date.

If you specifically wanted to create a countdown timer or stopwatch, you should create some state to track how much time remains, then subtract from that when the timer fires.

For example, we could create a countdown timer that shows time remaining in a label, like this:

struct ContentView: View {
    @State var timeRemaining = 10
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(timeRemaining)")
            .onReceive(timer) { _ in
                if timeRemaining > 0 {
                    timeRemaining -= 1
                }
            }
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to find which data change is causing a SwiftUI view to update | SwiftUI by Example

How to find which data change is causing a SwiftUI view to update
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
How to make SwiftUI modifiers safer to use with @warn_unqualified_access | SwiftUI by Example

How to make SwiftUI modifiers safer to use with @warn_unqualified_access

이찬희 (MarkiiimarK)
Never Stop Learning.