如何在Swift中将秒计时器连接到分钟计时器?

时间:2022-02-10 05:18:41

I have created a setupGame and subtractScore class for both minutes and seconds, so both the minutes and seconds timers work as of now. However, I cannot figure out how to make the minutes timer decrement by one every time the seconds timer gets to zero. Essentially I've tried to use if statements (e.g. if(seconds == 0) {minutes = minutes - 1}), but that has had no effect.

我已经为分钟和秒创建了一个setupGame和subtractScore类,所以分钟和秒计时器都是现在工作的。但是,我无法弄清楚每当秒计时器变为零时如何使分钟计时器减1。基本上我已经尝试使用if语句(例如if(seconds == 0){minutes = minutes - 1}),但这没有效果。

1 个解决方案

#1


I would not use separate timers. Have a seconds timer that fires once a second. It sounds like you want a count-down timer. So...

我不会使用单独的计时器。有秒计时器,每秒触发一次。听起来你想要一个倒计时器。所以...

Record the time when the timer starts using code like this:

使用以下代码记录计时器启动的时间:

let secondsToEnd = 60*5
let startInterval =  NSDate.timeIntervalSinceReferenceDate()
let endInterval = startInterval + Double(secondsToEnd)

Then in your timer code:

然后在您的计时器代码中:

let remainingSeconds = Int(endInterval - NSDate.timeIntervalSinceReferenceDate())
let minutes = remainingSeconds/60
let seconds = remainingSeconds%60

Display the minutes and seconds values however you need to.

显示您需要的分钟和秒值。

NSTimers will sometimes miss a firing if the app is busy when the timer should have gone off, and are not super-accurate. The above code will always calculate the real remaining amount of time, regardless of the timer you use to display that info and any inaccuracy in that timer.

如果应用程序在计时器应该关闭时忙,NSTimers有时会错过触发,并且不是超精确的。无论您用于显示该信息的计时器以及该计时器中的任何不准确,上述代码都将始终计算实际剩余时间。

#1


I would not use separate timers. Have a seconds timer that fires once a second. It sounds like you want a count-down timer. So...

我不会使用单独的计时器。有秒计时器,每秒触发一次。听起来你想要一个倒计时器。所以...

Record the time when the timer starts using code like this:

使用以下代码记录计时器启动的时间:

let secondsToEnd = 60*5
let startInterval =  NSDate.timeIntervalSinceReferenceDate()
let endInterval = startInterval + Double(secondsToEnd)

Then in your timer code:

然后在您的计时器代码中:

let remainingSeconds = Int(endInterval - NSDate.timeIntervalSinceReferenceDate())
let minutes = remainingSeconds/60
let seconds = remainingSeconds%60

Display the minutes and seconds values however you need to.

显示您需要的分钟和秒值。

NSTimers will sometimes miss a firing if the app is busy when the timer should have gone off, and are not super-accurate. The above code will always calculate the real remaining amount of time, regardless of the timer you use to display that info and any inaccuracy in that timer.

如果应用程序在计时器应该关闭时忙,NSTimers有时会错过触发,并且不是超精确的。无论您用于显示该信息的计时器以及该计时器中的任何不准确,上述代码都将始终计算实际剩余时间。