NStimer 倒计时延迟 1-2 秒

1-2 seconds delay in NStimer countdown

在 swift 2 中在线查找倒计时实现后,我找不到任何以倒计时方式工作的人。所以我自己做了,但是当它到达秒 01 时,需要 2 秒才能变成 59。例如,如果计时器打开 05:01,则需要 2 秒的滞后或计时器冻结,然后它变成 4:59。 看起来很奇怪,我是一个完全的初学者所以我的代码是一场灾难,这里是:

@IBOutlet var countDown: UILabel!
var currentSeconds = 59
var currentMins = 5
var timer = NSTimer()

 @IBAction func start(sender: UIButton) {
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

}

 func updateTime() {

    if (currentSeconds > 9)   {
        countDown.text = "0\(currentMins):\(currentSeconds)"
        currentSeconds -= 1
    } else if ( currentSeconds > 0) && (currentSeconds <= 9) {
        countDown.text = "0\(currentMins):0\(currentSeconds)"
        currentSeconds -= 1
    } else {
        currentMins -= 1
        currentSeconds = 59
    }

    if (currentSeconds == 0) && (currentMins == 0) {
        countDown.text = "time is up!"
        timer.invalidate()
    }



}

 @IBAction func stop(sender: AnyObject) {
  timer.invalidate()
 }

因为你忘记更新标签了:

if (currentSeconds > 9)   {
    countDown.text = "0\(currentMins):\(currentSeconds)"
    currentSeconds -= 1
} else if ( currentSeconds > 0) && (currentSeconds <= 9) {
    countDown.text = "0\(currentMins):0\(currentSeconds)"
    currentSeconds -= 1
} else {
    countDown.text = "0\(currentMins):00" // <-- missed this
    currentMins -= 1
    currentSeconds = 59
}

但是,如果您使用 NSDateFormatter 来格式化剩余秒数而不是管理 2 个单独的变量会更好:

class ViewController: UIViewController, UITextFieldDelegate {
    var secondsLeft: NSTimeInterval = 359
    var formatter = NSDateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

        formatter.dateFormat = "mm:ss"
        formatter.timeZone = NSTimeZone(abbreviation: "UTC")!
    }

    func updateTime()
    {
        countDown.text = formatter.stringFromDate(NSDate(timeIntervalSince1970: secondsLeft))
        secondsLeft -= 1

        if secondsLeft == 0 {
            countDown.text = "time is up!"
            timer.invalidate()
        }
    }
}