2014-10-19 29 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