如何在 AppDelegate 中定义的其他 class 中使用变量

How to use a variable in other class that is defined in AppDelegate

我在 class AppDelegate 内的 AppDelegate.swift 文件中有一个变量 var window: UIWindow?,我想在 class xyz 内的其他 class xyz.swift 文件中使用] 如此处 Get current view controller from the app delegate (modal is possible) 所述,但我在第一行遇到错误,我们将不胜感激。这是来自 xyz.swift

的代码
func CurrentView() -> UIView
  {
     let navigationController = window?.rootViewController as? UINavigationController // Use of Unresolved identifier 'window'
     if let activeController = navigationController!.visibleViewController {
     if activeController.isKindOfClass( MyViewController )  {
       println("I have found my controller!")
          }
      }
  }

即使我使用 let navigationController = AppDelegate.window?.rootViewController as? UINavigationController 错误也是 'AppDelegate.Type' does not have member named 'window'

这行代码在xyz.swift

  let navigationController = window?.rootViewController as? UINavigationController // Use of Unresolved identifier 'window'

您没有为 window 提供任何上下文,因此它应该在此 class 或全局变量中。

这更近了:

navigationController = AppDelegate.window?.rootViewController as? UINavigationController

并且您似乎意识到您需要在 AppDelegate 实例中引用 window 变量,但是您使用的语法引用了一个静态变量,而 window 是一个成员变量。

我建议您通读 swift 手册,更好地理解变量作用域,然后查看:

How do I get a reference to the app delegate in Swift?

您可能需要执行以下操作:

    var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let navigationController = appDelegate.window?....

正如@Dave Durbin 所指出的,您正试图将一个 class 中定义的变量用于另一个 class 中,而没有引用定义 class.