Member-only story
Timer in SwiftUI
Learn about how to build a timer, cancel a timer and restart a timer in SwiftUI
Timers are an essential component of many applications, and SwiftUI makes it easy to create and manage timers.
Lets’s look at how to build a timer, cancel a timer, and restart a timer in SwiftUI using the Timer
class.
Building a Timer
To build a timer in SwiftUI, we can use the Timer
class. The Timer
class provides an easy way to create a repeating or non-repeating timer. Here's an example of how to create a repeating timer that updates a counter every second:
struct ContentView: View {
@State private var counter = 0
var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Text("Counter: \(counter)")
.onReceive(timer) { _ in
self.counter += 1
}
}
}
In the code above, we have created a state variable counter
to keep track of the number of times the timer has fired. We have also created a timer that fires every second and updates the counter
variable.
The onReceive
modifier is used to update the counter
variable every time the timer fires.