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

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

    You can not resume the timer back. Instead of resuming - just create a new timer.

    class SomeClass : NSObject { // class must be NSObject, if there is no "NSObject" you'll get the error at runtime
    
        var timer = NSTimer()
    
        init() {
            super.init()
            startOrResumeTimer()
        }
    
        func timerAction() {
            NSLog("timer action")
        }
    
        func pauseTimer() {
            timer.invalidate
        }
    
        func startOrResumeTimer() {
            timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("timerAction"), userInfo: nil, repeats: true)
        }
    }
    

提交回复
热议问题