Swift中的全局函数调用?如何?

use*_*836 1 global function sprite-kit skscene swift

我对类方法调用有一个Swift noobie问题.我正在为我的孩子们使用Sprite Kit构建一个简单的学习应用程序.我在GameScene中定义了一个全局变量scoreCount,我几乎完成了所有游戏逻辑,例如检测正确答案和增加scoreCount.我也有GameOverScene.在两者上我都显示了分数 - 标签.我使用scoreCount参数(在GameScene中)保持得分.但是,由于我对Swift和Sprite Kit很陌生,我想知道如何在GameViewController中更新乐谱标签?所以基本上我想从GameScene调用GameViewController.updateLabels().

我知道这不是理想的方式,但请分享您的解决方案概念.谢谢!

Hao*_*aox 6

好.在你的GameViewController中你必须像这样在类func中转换你的func

class func yourFunc {
 //your code
}
Run Code Online (Sandbox Code Playgroud)

要从GameScene中调用它,只需输入以下代码:

GameViewController.yourFunc()
Run Code Online (Sandbox Code Playgroud)

不要忘记你正在创建一个全局函数,因此其中的所有变量也必须是全局的.

为你标签(全球):

var label:UILabel = UILabel()
Run Code Online (Sandbox Code Playgroud)

在你的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
Run Code Online (Sandbox Code Playgroud)

我希望它会对你有所帮助.