向窗口层次结构添加视图

7

我正在尝试在我的游戏中创建暂停屏幕。我已经在我的storyboard中添加了一个'PauseScreen'视图控制器,Storyboard ID和Restoration 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"上显示"暂停屏幕",而不是在"StartScreenViewController"上,但我不确定该如何实现。
1个回答

15

错误提示了问题的实际情况。

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
@Ethan 有时候你需要创建一个窗口来放置 UIAlertController:https://dev59.com/iF8d5IYBdhLWcg3wsDxW - Jeffery Thomas
你知道有哪些用 Swift 写的东西吗? - Ethan
@JefferyThomas 你真是个伟大的人,你是救星!过去三天我一直在寻找解决这个问题的方法。非常感谢你。 - Vinayak Bhor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接