2016-05-03 156 views
0

在網上查找快速2的countDown實現後,我找不到任何人在倒計時的方式工作。所以我做了我自己的,但是當它到達第二個01需要2秒變成59.例如,如果定時器在05:01需要2秒滯後或定時器凍結,則它變爲4:59。 它看起來奇怪,我是一個初學者,所以我的代碼是一場災難,那就是:1-2秒延遲NStimer倒計時

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

回答

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格式化剩餘秒數,而不是管理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() 
     } 
    } 
}