How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?

前端 未结 9 1672
甜味超标
甜味超标 2020-12-10 01:06

I\'m developing a game and I want to create a pause menu. Here is my code:

self.view?.paused = true

but NSTimer.scheduledTimerWithT

9条回答
  •  悲哀的现实
    2020-12-10 01:35

    You need to invalidate it and recreate it. You can then use an isPaused bool to keep track of the state if you have the same button to pause and resume the timer:

    var isPaused = true
    var timer = NSTimer()    
    @IBAction func pauseResume(sender: AnyObject) {     
        if isPaused{
            timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("somAction"), userInfo: nil, repeats: true)
            isPaused = false
        } else {
            timer.invalidate()
            isPaused = true
        }
    }
    

提交回复
热议问题