CountDown在swift中使用NSTimer

时间:2016-05-01 22:39:10

标签: swift nstimer countdown

我还在学习swift,我正在尝试设计一个应用程序,在一个部分我将这个游戏计时器设置为7分钟(将添加弄清楚如何让客户端稍后更改),现在是7点,我添加了2个按钮, 开始,暂停。我想让Start,启动countDown直到00:00,然后我打算添加一条弹出消息说时间到了!。

到目前为止

代码:

import UIKit

class ViewController: UIViewController {
@IBOutlet var countDown: UILabel!

var counter = 60
var timer = NSTimer()

func update() {

    if counter > 0 {
        countDown.text = String(counter--)
    }

}

@IBAction func start(sender: UIButton) {

    timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)

}

@IBAction func pause(sender: UIButton) {
     // timer.invalidate() stops the whole thing...
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

然而,应用程序继续崩溃......我不知道如何使计时器超过60秒,就像如何表示它。

1 个答案:

答案 0 :(得分:5)

这不是我做倒数计时器的方式。

@IBAction func start(sender: UIButton) {
     self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
     NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
    startTime = NSDate() // new instance variable that you would need to add.
}

func update() {
    let elapsedTime = NSDate().timeIntervalSinceDate(startTime)
    let currTime = totalTime - elapsedTime 
    //total time is an instance variable that is the total amount of time in seconds that you want
    countDown.text = String(currTime)
    if currTime < 0 {
        timer.invalidate()
        //do other stuff that you need to do when time runs out.
    }
}

还要确保您的IBAction插座在界面构建器中正确。