我正在尝试在我的游戏中创建一个暂停屏幕。我在 Storyboard中添加了一个“PauseScreen”viewController, Storyboard 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>,其 View 不在窗口层次结构中!
“StartScreenViewController”是我的开始屏幕的 View Controller ,也是初始 View Controller 。然后它转到“GameScene”,这是“PauseScreen”需要去的地方。如果我将初始 View Controller 设置为“GameViewController”/“GameScene”,它会起作用,所以我认为我需要更改第二行:
let currentViewController = (UIApplication.sharedApplication().delegate as AppDelegate)
以便它在“GameViewController”上显示“PauseScreen”,而不是在“StartScreenViewController”上显示,但我不确定该怎么做。
最佳答案
错误会准确告诉您发生了什么。
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
被呈现。根据您的描述:
The "StartScreenViewController" is the view controller… It then goes to the "GameScene"…
这一定是您的问题所在。你怎么去GameScene
来自 StartScreenViewController
?
我的猜测是您正在向应用程序添加一个新窗口。您需要设置 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:)
设置 Root View Controller 的动画。
关于swift - 将 View 添加到窗口层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608338/