如何将计时器添加到iOS应用程序,当计时器达到0时结束游戏?
我正在使用Swift制作一个测验应用程序。我想添加一个从60秒到1分钟的计时器,这样当它达到0时,游戏就结束了。如何添加计时器?这可以帮助您在updateTimer函数和stopCountDownTimer函数上设置适当的游戏逻辑如何将计时器添加到iOS应用程序,当计时器达到0时结束游戏?,ios,swift,Ios,Swift,我正在使用Swift制作一个测验应用程序。我想添加一个从60秒到1分钟的计时器,这样当它达到0时,游戏就结束了。如何添加计时器?这可以帮助您在updateTimer函数和stopCountDownTimer函数上设置适当的游戏逻辑 class TimerTestViewController: UIViewController { var totalSecondsCountDown = 60 // 60 seconds // timer var timer : NSTimer! overri
class TimerTestViewController: UIViewController {
var totalSecondsCountDown = 60 // 60 seconds
// timer
var timer : NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
self.startCountDownTimer()
}
func updateTimer() {
if self.totalSecondsCountDown > 0 {
self.totalSecondsCountDown = self.totalSecondsCountDown - 1
println("timer countdown : \(self.totalSecondsCountDown)")
}
else {
self.stopCountDownTimer();
println("timer stops ...")
}
}
func startCountDownTimer() {
if self.timer != nil {
self.timer.invalidate()
self.timer = nil
}
if self.totalSecondsCountDown > 0 {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTimer:", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
self.timer.fire()
}
}
func stopCountDownTimer() {
if self.timer != nil {
self.timer.invalidate()
self.timer = nil
}
}
}
看一看NSTimer类:欢迎来到SO!如果你在问题中加入更多的信息,你会得到更多的帮助和更少的反对票:你用谷歌搜索过吗?你有没有试过写一些可以放在帖子里的代码?我只是在谷歌上搜索了一下swift timer,第一个问题是:一般来说,我该如何做X?受到很多批评,部分原因是他们认为SO被用作谷歌的替代品。。。