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

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

    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
  • 2020-12-10 01:40

    SWIFT3

    Global Declaration :

     var swiftTimer = Timer()
     var count = 30
     var timer = Timer()
     @IBOutlet weak var CountDownTimer: UILabel!
    

    viewDidLoad

    override func viewDidLoad() { super.viewDidLoad() BtnStart.tag = 0 }

    Triggered IBACTION :

    @IBAction func BtnStartTapped(_ sender: Any) {
          if BtnStart.tag == 0 {
               BtnStart.setTitle("STOP", for: .normal)
               timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ScoreBoardVC.update), userInfo: nil, repeats: true)
    
               BtnStart.tag = 1
          } else {
    
               BtnStart.setTitle("START", for: .normal)
               timer.invalidate()
    
               BtnStart.tag = 0
          }                    
     }
    

    Function that Handles The things :

    func update(){
    
          if(count > 0){
               let minutes = String(count / 60)
               let ConvMin = Float(minutes)
               let minuttes1 = String(format: "%.0f", ConvMin!)
    
               print(minutes)
               let seconds = String(count % 60)
               let ConvSec = Float(seconds)
               let seconds1 = String(format: "%.0f", ConvSec!)
    
               CountDownTimer.text = (minuttes1 + ":" + seconds1)
               count += 1
          }          
     }
    
    0 讨论(0)
  • I was just working through a similar problem with my game, and found an easy solution.

    First I should point out like others have, that Timer and NSTimer doesn't have a pause function. You have to stop the Timer with Timer.invalidate(). After invalidating a Timer, you must initialize it again to start the Timer. To quote from https://developer.apple.com/documentation/foundation/timer, the function .invalidate() -

    Stops the timer from ever firing again and requests its removal from its run loop.


    To pause a timer we can use Timer.fireDate, this is where Timer (and NSTimer) saves the date for when the Timer will fire in the future.

    Here's how we can pause a Timer by saving the seconds left that the Timer has until it fires again.

    //The variable we will store the remaining timers time in
    var timeUntilFire = TimeInterval()
    
    //The timer to pause
    var gameTimer = Timer.scheduledTimer(timeInterval: delaysShow!, target: self, selector: #selector(GameClass.showRocket), userInfo: rocketid[i], repeats: false)
    
    func pauseTimer()
    {
        //Get the difference in seconds between now and the future fire date
        timeUntilFire = gameTimer.fireDate.timeIntervalSinceNow
        //Stop the timer
        gameTimer.invalidate()
    }
    
    func resumeTimer()
    {
        //Start the timer again with the previously invalidated timers time left with timeUntilFire
        gameTimer = Timer.scheduledTimer(timeInterval: timeUntilFire, target: self, selector: #selector(GameClass.showRocket), userInfo: rocketid[i], repeats: false)
    }
    

    Note: Don't invalidate() the Timer before getting the fireDate. After invalidate() is called the Timer seems to reset the fireDate to 2001-01-01 00:00:00 +0000.

    2nd Note: A timer can potentially fire after its set fireDate. This will lead to a negative number, which will default the Timer to run after 0.1 milliseconds instead. https://developer.apple.com/documentation/foundation/timer/1412416-scheduledtimer

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

    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)
    
    0 讨论(0)
  • 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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题