[英]Pausing timers when home button is pressed swift
我的GameScene.swift中有一堆计时器来调用函数。 当用户点击或双击主页按钮,收到短信等时,如何暂停这些计时器? 现在,当游戏运行时,在两次按下主屏幕按钮时,基于计时器的得分不断上升,并且仍然产生敌人。
//Spawn timer for enemy blocks
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
var scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
任何帮助将不胜感激!
编辑:我将这两行添加到我的GameViewController.swift
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseTimers:"), name:UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("startTimers:"), name:UIApplicationDidBecomeActiveNotification, object: nil)
然后这两个功能:
func pauseTimers(notification : NSNotification) {
println("Observer method called")
timer.invalidate()
scoretimer.invalidate()
}
func startTimers(notification : NSNotification) {
println("Observer method called")
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
}
但是,出现错误是因为在startTimers中重新创建计时器时,它们的选择器是我的GameScene.swift中的函数,而不是GameViewController.swift中的函数。 我怎样才能解决这个问题?
您可以通过在计时器上调用invalidate()
来停止计时器。 尽管无效的计时器将永远不会再次运行,但是如果您希望它再次触发,则需要稍后重新创建它。
要检测您的应用何时进入后台或被中断,以及何时回到前台,您可以侦听以下通知:
UIApplicationDidBecomeActiveNotification
UIApplicationWillResignActiveNotification
UIApplicationDidEnterBackgroundNotification
UIApplicationWillEnterForegroundNotification
当某个应用程序被覆盖时,该应用程序“退出活动状态”,例如,因为有来电提示或通知中心/控制中心已打开。 当另一个应用程序进入前台或显示主屏幕时,一个应用程序进入后台(从技术上讲,这也是一个应用程序)。
@更新
问题在于计时器的目标是self
,当您在GameViewController
,那么self
是GameViewController
实例。 您要么需要在GameScene
重新创建计时器,要么需要传递对GameScene
实例的引用,而不是将self
作为目标 。 选择器是被调用的方法, 目标是被调用该方法的对象,而self
始终是当前对象。
顺便说一句,可以在任何班级或多个班级同时收听这些通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.