vanagar
vanagar

Reputation: 3591

How can I indicate a view which has created with UIKit from a SKScene?

I have a file of SKScene which is named "MainScene.swift", and created a button on it for users to jump to another page. The another page was created not by SpriteKit but with UIKit. How can I indicate the target page and write codes in this case?

I usually do like this when jump to the other scene, if I created both pages with SpriteKit.

override func viewDidLoad() {
    super.viewDidLoad()

    let scene = MainScene(size: CGSize(width: 750, height: 1334))
    let skView = self.view as! SKView

    scene.scaleMode = .AspectFit
    skView.presentScene(scene)
}

And when I do the same thing on a scene which is created with UIKit, type a Storyboard ID on the Identity column, then code like this; I only know the way using storyboard.

class ViewController: UIViewController {
    @IBAction func gotoNewPage(sender: AnyObject) {
        let nextVC = self.storyboard?.instantiateViewControllerWithIdentifier("newPage")
    presentViewController(nextVC!, animated: false, completion: nil)    
    }
}

But when try same thing between the scene which is created SKScene and UIKit, I've no idea how to specify the latter from the former scene; I'm not sticking to use the storyboard. If there's any simple way, please let me know. Thank you in advance.

Upvotes: 1

Views: 195

Answers (1)

Mark Brownsword
Mark Brownsword

Reputation: 2307

This sounds like a job for the delegate pattern. Add a protocol for LevelScene;

// LevelScene.swift
protocol LevelScene : class {
    var gameDelegate: GameDelegate? { get set }
}

Add a protocol for GameDelegate;

// GameDelegate.swift
protocol GameDelegate : class {
    func gameOver()
}

In your mainScene add the protocol reference and create a property called gameDelegate;

class MainScene: SKScene, LevelScene {
    weak var gameDelegate: GameDelegate?
}

In your GameViewController add the protocol reference and implement the required protocol function - in this case it's called gameOver and seque to your UIKit View as usual;

class GameViewController: UIViewController, GameDelegate {
    func gameOver() {
        self.performSegue(withIdentifier: ExitGameSegueKey, sender: self)
    }
}

Set the delegate to gameViewController when presenting the scene;

scene.gameDelegate = self

Then in mainScene call the delegate function when required;

self.gameDelegate?.gameOver()

Upvotes: 1

Related Questions