Swift:暂停和恢复 NSTimer [英] Swift : Pause and Resume NSTimer

查看:136
本文介绍了Swift:暂停和恢复 NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这之前已经发布过,但我是 swift 的新手,我想根据我的情况寻求帮助.所以我需要运行一个计时器,当 stopMusic() 被调用时(在我的应用程序的某个地方),我需要暂停计时器,然后当 playMusic() 被调用时,我需要恢复计时器.

I know this has been posted before, but I'm new to swift and i would like to find help as per my situation. So i need to run a timer, and when the stopMusic() is called(somewhere in my app), i need to pause the timer, then when the playMusic() is called, i need to resume the timer.

这是我所拥有的:

override func viewDidLoad() {

runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(38.2, target: self, selector: "runAnimation", userInfo: nil, repeats: false)

}

func stopMusic() {
//Pause Timer
}

func playMusic() {
//Resume Timer
}

感谢您提供的任何帮助!!!

Thank you for any help you can provide!!!

推荐答案

简短回答:你不能.计时器无法暂停.

Short answer: You can't. Timers can't be paused.

相反,您需要在启动计时器时记录当前时间:

Instead you need to record the current time when you start the timer:

let startTime = NSDate.timeIntervalSinceReferenceDate()
let interval = 38.2
//Start your timer 
runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(interval, 
  target: self, 
  selector: "runAnimation", 
  userInfo: nil, 
  repeats: false)

然后,当您想暂停计时器时,将其设为无效并计算剩余时间:

Then, when you want to pause your timer, invalidate it and figure out how much time is left:

runFirstDropTimer.invalidate()
let elapsed = NSDate.timeIntervalSinceReferenceDate() - startTime
let remaining = interval - elapsed

最后,当您想恢复计时器时,请使用 remaining 值创建一个新计时器.

And finally when you want to resume your timer create a new timer with the remaining value.

这篇关于Swift:暂停和恢复 NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆