【问题标题】:How can I call a method from another swift file in GameViewController?如何从 GameViewController 中的另一个 swift 文件调用方法?
【发布时间】:2015-03-21 09:55:44
【问题描述】:

我在故事板中创建了一个按钮,该按钮位于我的游戏屏幕上。它在 GameViewController() 中有一个 IB 动作如下:

   @IBAction func buttonPressed(sender: AnyObject) {
        GameScene().myCustomMethod()
    }

在我的 GameScene 中存在 myCustomMethod(),它会生成敌人,但是上面的代码不能正常工作。如果我在 IBAction 中添加 println("button was pressed"),我会在控制台中打印出来,但 myCustomMethod 不会按预期执行并生成敌人。

谁能帮助我或解释如何解决我的问题?谢谢

【问题讨论】:

    标签: ios objective-c swift sprite-kit


    【解决方案1】:

    在您的方法中,您每次都创建一个新的GameScene 对象。您应该只创建一次(在初始化时),然后始终在此对象上调用 myCustomMethod

    var gameScene: GameScene!
    
    override func viewDidLoad() {
        gameScene = GameScene()
    }
    
    @IBAction func buttonPressed(sender: AnyObject) {
        gameScene.myCustomMethod()
    }
    

    【讨论】:

    • 谢谢,有道理!我只是在苦苦挣扎在 GameViewController 中在哪里初始化 gameScene = GameScene(),什么方法?
    • 您有initviewDidLoad 方法或类似的方法吗?
    • 我有 viewDidLoad 但我在顶级 GameViewController: UIViewController, UITextFieldDelegate { ... } 中遇到错误,说“GameViewController”类没有初始化程序。
    • 好的,我已经编辑了我的答案;如果你在viewDidLoad而不是init中分配变量gameScene,它应该是GameScene!类型(注意!
    • 谢谢,没有更多错误,但我仍然无法跨类更改值。例如我的按钮代码 @IBAction func buttonPressed(sender: AnyObject) { gameScene.booleanValue = true } 但如果我从 gameScene().update() 打印 booleanValue,则该值始终为 false。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2015-06-22
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多