Swift中的全局函数调用?如何? [英] Global function call in Swift? Howto?

查看:240
本文介绍了Swift中的全局函数调用?如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Swift noobie question on class method calls. I'm building a simple learning app for my kids using Sprite Kit. I have a global variable scoreCount defined in GameScene, where I pretty much do all my game logic such as detect correct answer and increment scoreCount. I also have GameOverScene. On both I show the Score -label. I'm keeping count of scores with the scoreCount-parameter (in GameScene). However as I'm quite new to Swift and Sprite Kit, I'm wondering how should I update the score label in GameViewController? So basically I would like to call GameViewController.updateLabels() from GameScene.

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

I know this isn't the ideal way but please share your solution concept on this. Thanks!

推荐答案

好. 在您的GameViewController中,您必须像这样

Well. In your GameViewController you have to transform your func in class func like this

class func yourFunc {
 //your code
}

要从您的GameScene调用此代码,请执行以下操作:

To call it from your GameScene just this code :

GameViewController.yourFunc()

别忘了您正在创建一个 global 函数,因此其中的所有变量也必须是全局的.

Don't forget you are creating a global function so all variables in it have to be global too.

为您标记(全局):

var label:UILabel = UILabel()

在您的GameViewController中:

in Your 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

我希望它能对您有所帮助.

I hope it will help you.

这篇关于Swift中的全局函数调用?如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆