How can I pause and resume NSTimer.scheduledTimerW

2019-01-18 22:08发布

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

self.view?.paused = true

but NSTimer.scheduledTimerWithTimeInterval still running..

 for var i=0; i < rocketCount; i++ {
 var a:NSTimeInterval = 1
 ii += a
 delaysShow =   2.0 + ((stimulus + interStimulus) * ii)       
 var time3 = NSTimer.scheduledTimerWithTimeInterval(delaysShow!, target: self, selector: Selector("showRocket:"), userInfo: rocketid[i]  , repeats: false)
 }

I want time3 to pause the timer when player click pause menu and continue run the timer when player come back to the game, but how can I pause NSTimer.scheduledTimerWithTimeInterval? help me please.

8条回答
时光不老,我们不散
2楼-- · 2019-01-18 22:31

Pause timer : timer.invalidate()

and

Resume timer : recreate timer. it's work fine.

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(mainController.updateTimer), userInfo: nil, repeats: true)
查看更多
倾城 Initia
3楼-- · 2019-01-18 22:32

To Start:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)

To Resume:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)

To Pause:

timer.invalidate

This worked for me. The trick is that do not look for something like "timer.resume" or "timer.validate". Just use "the same code for starting a timer" to resume it after the pause.

查看更多
登录 后发表回答