将视图添加到窗口层次结构

Ben*_*ill 6 viewcontroller presentviewcontroller swift xcode6

我正试图在我的游戏上创建一个暂停屏幕.我在故事板中添加了一个'PauseScreen'viewController,故事板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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

"StartScreenViewController"是我的开始屏幕的视图控制器,是初始视图控制器.然后转到"GameScene",这是"PauseScreen"需要去的地方.如果我将初始视图控制器设置为"GameViewController"/"GameScene",它可以工作,所以我认为我需要更改第二行:

let currentViewController = (UIApplication.sharedApplication().delegate as AppDelegate)
Run Code Online (Sandbox Code Playgroud)

所以它在"GameViewController"上呈现"PauseScreen",而不是"StartScreenViewController",但我不知道该怎么做.

Jef*_*mas 14

错误告诉您到底发生了什么.

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"......

这一定是你的问题所在.你如何去GameSceneStartScreenViewController

我的猜测是你要为应用程序添加一个新窗口.你需要设置rootViewController代替.

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

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

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

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