Timer with a button to plus one second per click.
To refresh our interface every 0.1 second, we should use a timer and declare how should the interface works.
The @State
recreates the interface every time the date is updated.
@State var timeCount: Double = 0.0
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {timer in
self.timeCount += 0.1
}
}
The timer should run like 0.1s, so we must create a function to format the time.
func timeString(time: Double) -> String {
return String(format: "%.1f", time)
}
Use onAppear
to initialize the timer.
Text(timeString(time: timeCount))
.onAppear(perform: {
let _ = self.timer
})