Hi there, I'm Marcos!

Back

Updating a view periodically

If you want to display a counter with the number of seconds passed since the view appeared on the screen you need to use a Timer that calls a function after the specified time has passed.

struct CounterView: View {
    @State var runningTime: Int = 0

    var body: some View {
        // ...
        .onAppear({ startCounting() })
    }

    func startCounting() {
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
      runningTime = getRunningTime()
    }
  }
}

If you want to stop updating the view you can store the timer in a variable and call the invalidate method on it:

struct CounterView: View {
    // ...
    @State var timer: Timer? = nil

    // ...

    func startCounting() {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
      runningTime = getRunningTime()
    }
  }

    func stopCounting() {
        if let _timer = timer {
      _timer.invalidate()
    }
    }
}