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

前端 未结 9 1652
甜味超标
甜味超标 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:50

    To start

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
    

    To pause

    timer.invalidate()
    

    To reset

    time += 1
    label.text = String(time)
    

    'label' is the timer on output.

    0 讨论(0)
  • 2020-12-10 01:50

    To stop it

      time3.invalidate() 
    

    To start it again

      time3.fire()
    
    0 讨论(0)
  • 2020-12-10 01:50

    Even though the solutions exposed here are good, I thought an important insight was missing. Like a lot of people here explained, timer invalidate() and recreate is the best option. But one could argue that you could do something like this:

    var paused:Bool
    
    func timerAction() {
        if !paused {
            // Do stuff here
        }
    }
    

    is easier to implement, but it will be less efficient.

    For energy impact reasons, Apple promotes avoiding timers whenever possible and to prefer event notifications. If you really need to use a timer, you should implement pauses efficiently by invalidating the current timer. Read recommendations about Timer in the Apple Energy Efficiency Guide here: https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html

    0 讨论(0)
提交回复
热议问题