无法启动计时器

时间:2016-01-17 02:57:39

标签: ios swift timer

我目前无法在我的应用中触发计时器。这是我的代码看起来像

func action() {
  //Paused
  timer.invalidate()

    let refreshAlert = UIAlertController(title: "Quit?", message: "Are you sure you want to quit?", preferredStyle: UIAlertControllerStyle.Alert)

    refreshAlert.addAction(UIAlertAction(title: "Yes!", style: .Default, handler: { (action: UIAlertAction!) in
        //Quit
    }))

    refreshAlert.addAction(UIAlertAction(title: "No!", style: .Default, handler: { (action: UIAlertAction!) in
        //Dismiss alert and resume game
        print("Fire")
        self.timer.fire()
        refreshAlert.dismissViewControllerAnimated(true, completion: nil)
    }))
}

action是暂停游戏时调用的内容。我首先使用timer.invalidate()停止计时器,然后显示一个警报,允许用户确认是否要退出。如果他们拒绝,我的目标是恢复计时器。这个问题是我被迫拨打self,我认为这与预先存在的timer.invalidate()冲突,因此导致计时器不fire。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

NSTimer失效后,无法重复使用。你需要创建一个新的来恢复它的射击周期。

答案 1 :(得分:0)

您必须创建一个新的timer。遗憾的是,你不能只使用fire来恢复它。

func action() {
 //Paused
 timer.invalidate()

let refreshAlert = UIAlertController(title: "Quit?", message: "Are you sure you want to quit?", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Yes!", style: .Default, handler: { (action: UIAlertAction!) in
    //Quit
}))

refreshAlert.addAction(UIAlertAction(title: "No!", style: .Default, handler: { (action: UIAlertAction!) in
    //Dismiss alert and resume game
    print("Fire")
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerOn", userInfo: nil, repeats: false)
    refreshAlert.dismissViewControllerAnimated(true, completion: nil)
}))

如果您想恢复timer,请查看以下问题:Resuming an NSTimer in Swift

它涉及使用CADisplayLink,这是可以恢复计时器的唯一方法。

相关问题