在 applicationDelegate 中初始化和分配视图控制器会使 viewController 中的所有 UI 元素为 nil

Initing and assigning a view controller in the applicationDelegate makes all the UI elements in the viewController be nil

在我的 ApplicationDelegate 中:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

        initMembers()
        runTutorialIfNeeded()
        return true
    }

 func initMembers()
    {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        mainViewController = InlineMainViewController()
        window?.rootViewController = mainViewController
        window?.makeKeyAndVisible()
    }

但是这一行导致了一个问题:

mainViewController = InlineMainViewController()

当代码到达override func viewDidLoad() {

时,所有UIElements都为nil

如果我评论这一行mainViewController = InlineMainViewController() 主情节提要中的所有 Ui 元素都不为零

我该如何解决这个问题? 我需要在 applicationDelegate 中保存主要 viewController 的引用,以便在 messageMgr: GNSMessageManager 发送事件时与其交互。

你初始化 ViewController 错误。如果您使用的是故事板,那么您应该这样写:

    let storyboard = UIStoryboard(name: "YourStoryBoardFileName", bundle: nil)
    mainViewController = storyboard.instantiateViewControllerWithIdentifier("your_VC_ID")
    window.rootViewController = mainViewController
    window.makeKeyAndVisible()

如果您正在使用 NIB/XIB 文件,那么您应该这样写:

let mainViewController = YourViewController(nibName:"YourVCNibName", bundle:nil)

如果您只是像 InLineViewController() 一样初始化它,则没有视图附加到它,因此一切都是 nil。