如何在SKScene的几个ViewController之间进行转换?

时间:2014-10-10 21:05:14

标签: ios swift sprite-kit viewcontroller skscene

我正在寻找使用SpriteKit从gameScene更改我的ViewController。 我有3个场景,有3个不同的ViewControllers。

当我的应用程序以PresentationViewController启动时(参见屏幕截图1),我的GameScene(GameViewController)到GameOverViewController的转换代码不起作用,我可以读取错误消息。 screenshot1

错误消息:

whose view is not in the window hierarchy!

我的代码是:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let settingController: UIViewController = storyboard.instantiateViewControllerWithIdentifier("PresentationViewController") as UIViewController
    let vc = self.view?.window?.rootViewController
    vc?.presentViewController(settingController, animated: true, completion: nil)

当我的应用程序以GameViewController启动时(请参阅屏幕截图2),转换代码可以正常运行。

screenshot2

我不知道为什么这2例之间存在差异。

有关信息,PresentationViewController和GameViewController之间的转换是使用带有以下代码的UIButton:

override func viewDidLoad() {

    super.viewDidLoad()

    var playButton   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    let image = UIImage(named: "playButton.png") as UIImage

    playButton.frame = CGRectMake(0, 0, 100, 100)
    playButton.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/1.7)
    playButton.addTarget(self, action: "transition:", forControlEvents: UIControlEvents.TouchUpInside)
    playButton.setBackgroundImage(image, forState: UIControlState.Normal)

    self.view.addSubview(playButton)

}

func transition(sender:UIButton!)
{

    println("transition")
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("GameViewController") as UIViewController

    secondViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
    self.presentViewController(secondViewController, animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:2)

我自己找到了一种在几个ViewController之间导航的方法。 我将secondViewController设置为rootViewController,以替换我的PresentationViewController文件func transition()中的此代码:

self.presentViewController(secondViewController, animated: true, completion: nil)` 

通过此代码(带选项):

secondViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
let window = UIApplication.sharedApplication().windows[0] as UIWindow
UIView.transitionFromView(
    window.rootViewController!.view,
    toView: secondViewController.view,
    duration: 0.65,
    options: .TransitionCrossDissolve,
    completion: {
        finished in window.rootViewController = secondViewController
})