繁体   English   中英

如何在swift中暂停和恢复NSTimer.scheduledTimerWithTimeInterval?

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

我正在开发一款游戏,我想创建一个暂停菜单。 这是我的代码:

self.view?.paused = true

但是NSTimer.scheduledTimerWithTimeInterval仍在运行......

 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)
 }

我希望time3在玩家点击暂停菜单时暂停计时器并在玩家回到游戏时继续运行计时器,但我怎么能暂停NSTimer.scheduledTimerWithTimeInterval 请帮帮我。

您需要使其无效并重新创建它。 然后,如果您有相同的按钮可以暂停和恢复计时器,则可以使用isPaused bool来跟踪状态:

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
    }
}

阻止它

  time3.invalidate() 

再来一次

  time3.fire()

开始:

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

恢复:

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

暂停:

timer.invalidate

这对我有用。 诀窍是不要寻找像"timer.resume""timer.validate"这样的东西。 只需使用“相同的代码启动计时器”即可在暂停后恢复计时器

开始

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

暂停

timer.invalidate()

重置

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

'label'是输出的计时器。

你无法恢复计时器。 而不是恢复 - 只需创建一个新的计时器。

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)
    }
}

SWIFT3

全球宣言:

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

viewDidLoad中

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

触发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
      }                    
 }

处理事物的功能:

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
      }          
 }

我刚刚在游戏中遇到了类似的问题,并找到了一个简单的解决方案。

首先我应该像其他人一样指出,Timer和NSTimer没有暂停功能。 您必须使用Timer.invalidate()停止Timer。 使定时器无效后,必须再次初始化它以启动定时器。 引自https://developer.apple.com/documentation/foundation/timer ,函数.invalidate() -

停止计时器再次发射并请求从其运行循环中删除它。


要暂停计时器,我们可以使用Timer.fireDate,这是Timer(和NSTimer)保存计时器将来触发的日期的地方。

这是我们如何通过保存定时器剩余的秒数直到它再次触发来暂停定时器。

//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)
}

注意:在获取fireDate之前,不要使Timer无效。 调用invalidate()后,Timer似乎将fireDate重置为2001-01-01 00:00:00 +0000。

第二个注意:计时器可能会在设置fireDate后触发。 这将导致负数,这将默认Timer在0.1毫秒后运行。 https://developer.apple.com/documentation/foundation/timer/1412416-scheduledtimer

暂停计时器:timer.invalidate()

恢复计时器:重新创建计时器。 它的工作正常。

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

尽管这里公开的解决方案很好,但我认为缺少一个重要的见解。 像这里解释的很多人一样,timer invalidate()和recreate是最好的选择。 但有人可能会说你可以这样做:

var paused:Bool

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

更容易实现,但效率会降低。

出于能源影响的原因,Apple会尽可能地避免使用计时器,并且更喜欢事件通知。 如果您确实需要使用计时器,则应通过使当前计时器无效来有效地实现暂停。 在Apple Energy Efficiency Guide中阅读有关计时器的建议: https//developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM