gpt4 book ai didi

ios - 在 GameScene.swift 中更改 GameViewController.swift 对象的属性

转载 作者:行者123 更新时间:2023-11-28 12:51:39 26 4
gpt4 key购买 nike

我是 Swift 的新手,很抱歉,如果这看起来是一个显而易见的问题。

我正在尝试用 Swift 编写游戏,我在 Storyboard 中设计了一个标签和一个播放按钮。

Main.storyboard

我在 GameViewController.swift 文件中添加了对这些对象的引用,如下所示:

// MARK: Objects
@IBOutlet var gameLabel: UILabel!
@IBOutlet var playButton: UIImageView!

// MARK: Actions

@IBAction func playButtonTapped(sender: UITapGestureRecognizer) {
GameScene().gameStart()
}

这属于 GameViewController 类:class GameViewController: UIViewController

但是,主要游戏本身发生在 GameScene.swift 中。这涉及到我必须在游戏开始后立即隐藏标签和图像。我不确定如何设置这些对象的属性以隐藏,因为如果我在 GameScene.swift 中执行以下操作:

GameViewController().playButton.hidden = true

...游戏因 fatal error 而崩溃。错误显示: fatal error :在展开可选值时意外发现 nil

有没有人对这个问题有建议?任何帮助深表感谢。抱歉,如果信息难以理解。

干杯。

最佳答案

您正在创建 'GameViewController() 的新实例,但您希望使用已经存在的实例。如果您只想创建一个GameViewController`(可能是这种情况),您可以使用静态实例变量。

GameViewController 中,放置:

static var instance: GameViewController!

viewDidLoad() 中,放入:

GameViewController.instance = self

最后,在您的 GameScene 中,将 GameViewController() 切换为 GameViewController.instance

关于ios - 在 GameScene.swift 中更改 GameViewController.swift 对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com