【发布时间】:2016-01-08 06:20:30
【问题描述】:
我是 swift & spritekit 的新手,想知道如何检测主页按钮是否被按下?
主要问题是我有 NSTimer.scheduledTimerWithTimeInterval 运行以在 didMoveToView 中生成多个字符,一切进展顺利,但是当我用主页按钮暂停游戏并在几秒钟后重新启动游戏时,字符泛滥很多。我假设 NSTimer 没有被暂停,因此在重新启动应用程序时会出现大量字符。我想知道一个简单的解决方案和示例,当按下主页按钮时我将如何暂停,并在应用程序重新启动时恢复?我很想从你这里!
testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
///这是在didMoveToView中生成字符的部分项目代码
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appEnterIntoBackGround:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appBecomeActive:"), name:UIApplicationWillEnterForegroundNotification, object: nil)
//start the timer and calls the timerUpdate method every 1.0 seconds
myTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
if(skview.level == 3) {
myTimer2 = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
}
testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
}
func appEnterIntoBackGround(notification : NSNotification) {
let skview = self.view as! GameSKView!
print("App is in Background")
testEnemy.invalidate() //remove timer here when add enter into background.
if(skview.level == 3) {
myTimer2.invalidate()
}
myTimer.invalidate()
}
func appBecomeActive(notification : NSNotification) {
let skview = self.view as! GameSKView!
// print("App is active now")
//add your timer again when app enter into foreground
testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,target: self,selector: "timerUpdate",userInfo: nil,repeats: true)
if(skview.level == 3) {
myTimer2 = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
}
testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,
target: self,
selector: "timerUpdate",
userInfo: nil,
repeats: true)
}
【问题讨论】:
-
这就是为什么在这种情况下 SKAction 比 NSTimer 更受欢迎(如果视图或场景暂停,NSTimer 不会受到影响)。在这里阅读更多:stackoverflow.com/q/23978209/3402095
-
没想到!谢谢你的信息!真的很有帮助!
标签: ios swift sprite-kit