【问题标题】:Global function call in Swift? Howto?Swift 中的全局函数调用?如何?
【发布时间】:2014-10-19 09:56:23
【问题描述】:

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

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

【问题讨论】:

    标签: function swift sprite-kit global skscene


    【解决方案1】:

    嗯。 在您的 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
    

    希望对你有所帮助。

    【讨论】:

    • 这确实对我有帮助,但我仍然无法将我的标签作为全局变量引入。如果我将标签移到课堂之外:@IBOutlet weak var livesCounter: UILabel!我得到:“只有实例属性可以声明为 'IBOutlet'”
    • 你使用情节提要吗?
    • 是的,在情节提要上创建了标签并使用助手编辑器将它们拖到代码中。
    • 好的。您可以在没有情节提要的情况下直接对它们进行编码。像这样,您将能够将它们设置为全局。从情节提要中删除它们,并在 GameViewController 中删除 @IBOutlet weak。在类外声明你的变量var livesCounter:UILabel!
    • 如果您需要,我可以帮助您设置标签属性
    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多