swift - View Controller 不更新

标签 swift uiviewcontroller viewdidload viewwillappear

我有 2 个 UIViewController,一个启动 GameScene,另一个应该显示高分,如下所示。问题是我的第二个 UIViewController 不想显示更新的高分。它只是一直显示0。 有谁知道问题是什么?我尝试使用 viewDidLoad 和 viewWillAppear 但它们都不起作用。

override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
        label.center = CGPoint(x: 160, y: 285)
        label.textAlignment = .center
        label.text = String(GameScene().highScore)
        self.view.addSubview(label)

    }

在 GameScene 中,我已将 highScore 声明为:

var highScore = Int()

并在 gameOver 函数中使用,如下所示:

if score > highScore {highScore = score}

谢谢

最佳答案

label.text = String(GameScene().highScore)

这句话表明 GameScene 是一个静态类。除非是这样,否则您根本无法以这种方式访问​​变量。

您将需要在 View Controller 之间传递数据以在场景之间传递数据。您可以使用以下三个选项之一传递数据:

  1. 尽管有performSegue()
  2. 执行SegueWithIdentifier()并在IB中建立连接
  3. 在 IB 中建立连接并定义操作

关于swift - View Controller 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101407/

相关文章:

string - Swift,使用字符串名称来引用变量

ios - 根据控制台,委托(delegate)似乎没有工作

ios - 如何使用委托(delegate)在其他 Storyboard 中的 vc 的 MainStoryboard 中显示 ViewController?

ios - 我是否正确使用委托(delegate)?如果没有,我应该怎么做?

ios - 只有一个预期的两个 viewDidLoad 消息

ios - 核心数据位置文件

c# - 更改呈现 View Controller 约束

ios - 在 viewDidLoad 中注册通知

ios - 在 viewDidLoad 中运行 MPMoviePlayerController 的奇怪行为

swift - 我的字符串扩展在 appDelegate 之前运行,为什么会这样?