【问题标题】:How to call a different class from the app delegate (using SpriteKit) in Swift如何在 Swift 中从应用程序委托(使用 SpriteKit)调用不同的类
【发布时间】:2015-10-07 18:43:27
【问题描述】:

我需要从 AppDelegate 类中名为 applicationDidEnterBackground 的默认方法调用 GameScene 类中名为 pause() 的方法。

换句话说(在 AppDelegate 中):

func applicationDidEnterBackground(application: UIApplication) {
    // Call GameScene method
}

在 GameScene 类中:

func pause() {
    // pause game     (this method works fine when called elsewhere in the program)
}

我需要在应用进入后台时调用pause()

GameScene.pause() 不起作用,但我不明白为什么。非常感谢任何帮助。

【问题讨论】:

  • GameScene.pause() 不起作用,因为您是在类上调用它,而不是在类的实例上调用它,而且它不是类方法 - 它是实例方法。您需要引用类的实例来调用它。您的 GameScene 对象在哪里以及如何实例化?
  • var scene: GameScene! 属于 GameViewContoller 类。然后在viewDidLoad 方法中:scene = GameScene(size: skView.bounds.size)。我希望这能回答你的问题!
  • 这意味着它在 AppDelegate 中不可访问,这是一个不同的类。
  • 那么我该如何解决这个问题?
  • 等一下,答案来了

标签: ios swift sprite-kit swift2


【解决方案1】:

这里最简单的解决方案可能是使用NSNotificationCenter,完全避免使用UIApplicationDelegate回调

将以下内容添加到您的GameViewController-viewDidLoad

NSNotificationCenter.defaultCenter().addObserver(self, selector: "appEnteredBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)

请注意,“appEnteredBackground:”参数字符串的末尾有一个 : - 如果你错过了它,这将不起作用(因为它会寻找一个没有参数的方法

添加以下 deinit 析构函数(如果您已经有,则添加相关行):

deinit {
  NSNotificationCenter.defaultCenter().removeObserver(self)
}

然后在GameViewController上实现-appEnteredBackground:方法:

func appEnteredBackground(notification:NSNotification) {
  scene.pause()
}

应用进入后台时应该触发通知方法

【讨论】:

  • 谢谢!这解决了我的问题。你真是个天才。
  • 谢谢哥们!帮了大忙!
  • 值得注意的是,您可能不再需要deinit 方法。 Apple says "如果您的应用面向 iOS 9.0 及更高版本,则无需在其 dealloc 方法中取消注册观察者"。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多