【问题标题】:Adding a view to the window hierarchy将视图添加到窗口层次结构
【发布时间】:2014-12-22 18:24:31
【问题描述】:

我正在尝试在我的游戏中创建暂停屏幕。我在情节提要中添加了一个“PauseScreen”视图控制器,情节提要 ID 和恢复 ID 设置为“PauseScreenID”,并移动到暂停屏幕,我在“GameScene”中创建了该功能:

func pauseSceenTransition(){

    let viewController = UIStoryboard(name: "Main", bundle:nil).instantiateViewControllerWithIdentifier("PauseScreenID") as UIViewController

    let currentViewController = (UIApplication.sharedApplication().delegate as AppDelegate)

    currentViewController.window?.rootViewController?.presentViewController(viewController, animated: false, completion: nil)
}

但是当它被调用时,我得到了错误:

警告:尝试在 AppName.StartScreenViewController: 0x7fae61f79980> 上显示 AppName.PauseScreen: 0x7fae61fe5ff0>,其视图不在窗口层次结构中!

“StartScreenViewController”是我的开始屏幕的视图控制器,也是初始视图控制器。然后它转到“GameScene”,这是“PauseScreen”需要去的地方。如果我将初始视图控制器设为“GameViewController”/“GameScene”,它会起作用,所以我认为我需要更改第二行:

let currentViewController = (UIApplication.sharedApplication().delegate as AppDelegate)

所以它在“GameViewController”上显示“PauseScreen”,而不是在“StartScreenViewController”上,但我不知道该怎么做。

【问题讨论】:

    标签: swift xcode6 viewcontroller presentviewcontroller


    【解决方案1】:

    错误告诉你到底发生了什么。

    Warning: Attempt to present <AppName.PauseScreen: 0x7fae61fe5ff0> on <AppName.StartScreenViewController: 0x7fae61f79980> whose view is not in the window hierarchy!

    (UIApplication.sharedApplication().delegate as AppDelegate).window?.rootViewController 指向StartScreenViewController 的一个实例。这很糟糕:rootViewController 应该指向 GameScene 的一个实例。

    根本原因必须是GameScene 的呈现方式。根据您的描述:

    “StartScreenViewController”是视图控制器……然后转到“GameScene”……

    这一定是你的问题所在。怎么从StartScreenViewController转到GameScene

    我的猜测是您正在向应用程序添加一个新窗口。您需要改为设置rootViewController

    let gameScene = UIStoryboard(name: "Main", bundle:nil).instantiateViewControllerWithIdentifier("GameSceneID") as UIViewController
    let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    appDelegate.window?.rootViewController = gameScene
    

    当您返回开始屏幕时,您再次设置rootViewController

    let initialViewController = UIStoryboard(name: "Main", bundle:nil).instantiateInitialViewController() as UIViewController
    let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    appDelegate.window?.rootViewController = initialViewController
    

    您可以使用transitionFromViewController(,toViewController:, duration:, options:, animations:, completion:) 设置根视图控制器的动画。

    【讨论】:

    • 嗨,我现在遇到了同样的问题,我很好奇解决方案在过去一年半中是否发生了变化。我正在尝试从按钮内的嵌套if 中调用UIAlertController。按钮中的常规if 语句显示UIAlertView 的罚款,但这些if 语句的true 结果与上述相同。
    • @Ethan 有时您需要创建一个窗口来将UIAlertController 放入:stackoverflow.com/questions/26554894/…
    • 你知道的任何东西都是用swift写的吗?
    • @JefferyThomas 伟人你是救世主!!最近三天我正在寻找这个问题的解决方案。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2016-09-03
    相关资源
    最近更新 更多