[英]How using class func to call a method from another class in SWIFT
我想从GameViewController调用我的计时器方法(用GameScene编写),以便使用在GameViewController类中初始化的UIButton暂停游戏。
我正在尝试使用这样的class func
:
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
GameScene.startTimer()
}
class func startTimer(){
timerCount = NSTimer.scheduledTimerWithTimeInterval(1.0
, target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
}
func updateTimer(dt:NSTimer){
counter--
counterGame++
if counter<0{
timerCount.invalidate()
removeCountDownTimerView()
} else{
labelCounter.text = "\(counter)"
}
if counterGame>20{
balloon.size = CGSizeMake(50, 50)
}
if counterGame>40{
self.physicsWorld.gravity = CGVectorMake(0, -0.8)
}
if counterGame>60{
self.physicsWorld.gravity = CGVectorMake(0, -1)
}
}
func removeCountDownTimerView(){
defaults.setInteger(balloonDestroyed, forKey: "score")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let settingController: UIViewController = storyboard.instantiateViewControllerWithIdentifier("GameOverViewController") as UIViewController
let vc = self.view?.window?.rootViewController
vc?.presentViewController(settingController, animated: true, completion: nil)
}
}
但是这段代码返回一个错误:
[Funfair_balloon.GameScene updateTimer:]: unrecognized selector sent to class 0x10b13d940
当我不使用class func
该应用程序可以完美运行,但无法使用UIButton停止计时器。 我做错了什么?
请注意,在使用class func
,不能使用在该类中初始化的变量。
因此,例如,如果变量timerCount
在GameScene
类中已初始化,则不能使用它。
我不确定为什么要使用类函数。 以下内容应仅使用GameScene
的当前实例进行工作。 请注意, var timerCount
是可选的(因为您不能轻易地覆盖init
),直到在startTimer()
创建它时为止,因此最终使它无效时,必须将其拆开。
class GameScene: SKScene, SKPhysicsContactDelegate {
var timerCount: NSTimer? = nil
var counter = 100 // or whatever
override func didMoveToView(view: SKView) {
self.startTimer()
}
func startTimer() {
self.timerCount = NSTimer.scheduledTimerWithTimeInterval(1.0
, target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
}
func updateTimer(dt: NSTimer) {
// Do stuff
counter--
if counter < 0 {
self.timerCount!.invalidate() // or dt.invalidate()
self.removeCountDownTimerView()
} else {
// update counter label
}
// Do more stuff
}
func removeCountDownTimerView() {
// Do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.