Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将计时器添加到iOS应用程序,当计时器达到0时结束游戏?_Ios_Swift - Fatal编程技术网

如何将计时器添加到iOS应用程序,当计时器达到0时结束游戏?

如何将计时器添加到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

我正在使用Swift制作一个测验应用程序。我想添加一个从60秒到1分钟的计时器,这样当它达到0时,游戏就结束了。如何添加计时器?

这可以帮助您在updateTimer函数和stopCountDownTimer函数上设置适当的游戏逻辑

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被用作谷歌的替代品。。。