如何在swift中暂停和恢复NSTimer.scheduledTimerWithTimeInterval? [英] How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?

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

问题描述

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

I'm developing a game and I want to create a pause menu. Here is my code:

self.view?.paused = true

但是NSTimer.scheduledTimerWithTimeInterval仍在运行..

but NSTimer.scheduledTimerWithTimeInterval still running..

 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?请帮助我。

I want time3 to pause the timer when player click pause menu and continue run the timer when player come back to the game, but how can I pause NSTimer.scheduledTimerWithTimeInterval? help me please.

推荐答案

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

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

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

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