2016-05-03 2 views
0

すぐに2のcountDownの実装をオンラインで見た後、カウントダウンの方法で動作するものは見つかりませんでした。だから私は自分自身を作ったが、2番目の01に達すると59秒に2秒かかります。たとえば、タイマーが05:01にある場合は、2時間の遅れやタイマーのフリーズが発生し、それは4:59になります。 それは私のコードは、災害であるので、私は完全な初心者だけど、奇妙に見えますが、ここにある:NStimerのカウントダウンで1-2秒遅れました

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