2014-10-19 27 views
1

我有類方法調用的Swift noobie問題。我正在使用Sprite Kit爲我的孩子構建一個簡單的學習應用程序。我在GameScene中定義了一個全局變量scoreCount,其中我幾乎可以做所有的遊戲邏輯,比如檢測正確答案和增加scoreCount。我也有GameOverScene。在兩個我都顯示Score -label。我使用scoreCount參數記錄了分數(在GameScene中)。然而,因爲我對Swift和Sprite Kit相當陌生,所以我想知道如何更新GameViewController中的分數標籤?所以基本上我想從GameScene調用GameViewController.updateLabels()。在Swift中調用全局函數?如何?

我知道這不是理想的方式,但請分享您的解決方案的概念。謝謝!

回答

5

好吧。 在你GameViewController,你必須改變你的FUNC類FUNC這樣

class func yourFunc { 
//your code 
} 

要從GameScene調用它只是驗證碼:

GameViewController.yourFunc() 

不要忘記你正在創建一個全球函數,因此它中的所有變量也必須是全局的。

對於你的標籤(全局):

var label:UILabel = UILabel() 
在你GameViewController

class GameViewController : UIViewController { 
    override func viewDidLoad() { 
    super.viewDidLoad() 

    label.text = "bonjour" // to set the text 
    label.frame = CGRectMake(0, 0, 100, 100)/set the position AND size CGRectMake (x, y, width, heigth) 

    label.textColor = UIColor.redColor() // set your color 
    label.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2) // set the position from x=0 and y=0 
    self.view.addSubview(label) // add the label to your screen 

我希望這會幫助你。

+0

這確實幫了我,但我仍然堅持不能將我的標籤作爲全局變量引入。如果我將該標籤移動到類的外部:@IBOutlet weak var livesCounter:UILabel!我得到:「只有實例屬性可以聲明'IBOutlet'」 – user3673836 2014-10-19 10:20:42

+0

你使用故事板嗎? – Haox 2014-10-19 10:23:20

+0

是的,創建故事板上的標籤並使用助理編輯器將其拖動到代碼中。 – user3673836 2014-10-19 10:24:56