【问题标题】:1-2 seconds delay in NStimer countdownNStimer 倒计时延迟 1-2 秒
【发布时间】:2016-05-03 22:24:39
【问题描述】:

在网上寻找 swift 2 中的 countDown 实现后,我找不到任何以倒计时方式工作的人。所以我自己做了,但是当它到达秒 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()
 }

【问题讨论】:

    标签: swift2 nstimer countdown stopwatch


    【解决方案1】:

    因为你忘记更新标签了:

    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 格式化剩余秒数,而不是管理两个单独的变量:

    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()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-17
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多