0

My simple timer is defined as:

let now = Date.now
var start = Calendar.current.date(byAdding: .second, value: Int(16), to: now)!
var end = Calendar.current.date(byAdding: .second, value: Int(16), to: start)!
 
Text(timerInterval: start...end, countsDown: false)

I was expecting to start counting it like: 00:16, 00:17, 00:18 ... 00:32.

But it works like 00:00, 00:01 ... 00:16 and starts counting 16 seconds after load.

How can I start it from given interval and end on a given interval from future?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Does this answer your question? [SwiftUI - How to Make A Start/Stop Timer](https://stackoverflow.com/questions/63548432/swiftui-how-to-make-a-start-stop-timer) – Yrb Apr 09 '23 at 18:02
  • You can't. That is a limited convenience initializer. You are going to have to use your own timer. – Yrb Apr 09 '23 at 18:03
  • @Yrb, no, there is a simple solution and answer for my question. That question is not about to start/stop timer. Please read the question again;) – Bartłomiej Semańczyk Apr 09 '23 at 20:39
  • Yes, and that solution is to use a Timer to display the countdown. You missed the part in the answers where they display the countdown. – Yrb Apr 09 '23 at 20:42
  • No, that simple solution is WITHOUT timer. That way I can start from given Interval and count it down or up every second. – Bartłomiej Semańczyk Apr 09 '23 at 20:44

1 Answers1

0

This should achieve what you'd like. You need to subtract 16 from now so the timer knows to start from 16s in the past. The timer is always relative to now.

let now = Date.now
var start = Calendar.current.date(byAdding: .second, value: Int(-16), to: now)!
var end = Calendar.current.date(byAdding: .second, value: Int(16), to: start)!
 
Text(timerInterval: start...end, countsDown: false)
Kyle Venn
  • 4,597
  • 27
  • 41