我有一个关于类方法调用的 Swift 菜鸟问题。我正在使用 Sprite Kit 为我的 child 构建一个简单的学习应用程序。我在 GameScene 中定义了一个全局变量 scoreCount,我几乎在其中执行所有游戏逻辑,例如检测正确答案和增加 scoreCount。我也有 GameOverScene。在两者上,我都显示了 Score -label。我使用 scoreCount 参数(在 GameScene 中)计算分数。然而,由于我对 Swift 和 Sprite Kit 还很陌生,我想知道我应该如何更新 GameViewController 中的得分标签?所以基本上我想从 GameScene 调用 GameViewController.updateLabels()。
我知道这不是理想的方式,但请分享您的解决方案概念。谢谢!
最佳答案
嗯。 在您的 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
希望对您有所帮助。
关于function - Swift 中的全局函数调用?如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449343/