好的,所以我正在开发一个倒数计时器功能,这是我正在开发的应用程序的一部分。我在如何实现计时器及其在屏幕上的显示方式时遇到了一个问题。我的两个问题是
如果有什么我不清楚的地方,问一下。
MyCtrl
答案 0 :(得分:1)
如果要通过seconds
变量的减量值手动计算秒数,则是个坏主意。因为Timer
不保证它会在1秒间隔后准确触发。
我认为,首选方法是计算计时器启动时间与当前时间之间的时间间隔。
class ViewController: UIViewController {
@IBOutlet weak var minuteLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
var timer: Timer?
let countDownInterval: TimeInterval = 10*60 // minutes*seconds
var finishTime: Date!
var pauseStartTime: Date?
@IBAction func startTimer(_ sender: UIButton) {
if let pause = pauseStartTime {
let pauseInterval = Date().timeIntervalSince(pause)
finishTime.addTimeInterval(pauseInterval)
} else {
finishTime = Date().addingTimeInterval(countDownInterval)
}
pauseStartTime = nil
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] _ in self?.changeLabels() })
}
@IBAction func pauseTimer(_ sender: UIButton) {
pauseStartTime = Date()
timer?.invalidate()
}
func changeLabels() {
let currentTime = Date()
guard currentTime < finishTime else {
// Countdown finished
timer?.invalidate()
minuteLabel.text = String(format: "%02.f", 0)
secondLabel.text = String(format: "%02.f", 0)
return
}
let currentInterval = finishTime.timeIntervalSince(currentTime)
let minutes = (currentInterval / 60).rounded(.down)
let seconds = currentInterval.truncatingRemainder(dividingBy: 60).rounded()
minuteLabel.text = String(format: "%02.f", minutes)
secondLabel.text = String(format: "%02.f", seconds)
}
}