簡體   English   中英

如何使用類func從SWIFT中的另一個類調用方法

[英]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 ,不能使用在該類中初始化的變量。

因此,例如,如果變量timerCountGameScene類中已初始化,則不能使用它。

我不確定為什么要使用類函數。 以下內容應僅使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM