Martin Mikusovic
Martin Mikusovic

Reputation: 1070

Moving between GameScene and ViewController Swift

I want to move from my GameScene to ViewController, when I touch an Image and back to GameScene when I touch an UIButton. It worked from ViewController to GameScene, because it is UIButton.

I have done it like this:

@IBAction func playbut(sender: UIButton) {
    var scene = GameScene(size: CGSize())
    let skView = self.view as! SKView!
    skView.ignoresSiblingOrder = true
    scene.scaleMode = .ResizeFill
    scene.size = skView.bounds.size
    skView.presentScene(scene)
}

But I don't know what code to write to go back to ViewController, when I touch that image, which is on GameScene.

What should I write to GameScene?

Thanks

Upvotes: 2

Views: 3905

Answers (2)

Harsh Patel
Harsh Patel

Reputation: 3

Please use the following.

let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc = mainStoryboard.instantiateViewController(withIdentifier: "MainController") let vc2 = self?.view!.window?.rootViewController?.presentedViewController vc2?.present(vc, animated: true, completion: nil)

Using Constant

self?.view!.window?.rootViewController?.presentedViewController

we can derive view controller in which our current game scene is running.

Upvotes: 0

BAP
BAP

Reputation: 1402

I don't think this is what you're expected to do... You should be using an SKScene - instead of a UIViewController - for your navigation/menu.

But, one post I found did explain this (albeit it's in Obj-C):

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone"     bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"PurchasedVC"];
//Call on the RootViewController to present the New View Controller
[self.view.window.rootViewController presentViewController:vc animated:YES completion:nil];

The Swift version should look something like this (I'm no expert, but the syntax isn't too bad)...

var mainStoryboard = UIStoryboard(name: "Main_iPhone", bundle: nil)
var vc = mainStoryboard.instantiateViewControllerWithIdentifier("PurchasedVC") as! UIViewController
self.view.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)

In terms of other answers:

I hope that helps. I had the same question, and to be honest, it looks like I was just doing it wrong the whole time!

Upvotes: 2

Related Questions