Instantiate a *game scene* view Swift

戏子无情 提交于 2019-12-13 04:52:32

问题


So, I am trying to instantiate a view controller. The issue is, that the view that I am trying to instantiate is a gameScene view controller (Sprite Kit). Also, the view that I am instituting from is also a gameScene view. If I were instantiating from a normal UIViewController, I would do this:

let vc : AnyObject! = self.storyboard!.instantiateViewControllerWithIdentifier("main")
self.showViewController(vc as! UIViewController, sender: vc)
//the view that I am instantiating's class name is "GameScene"

When I try to run this, I get two errors:

gameScene does not have member named "storyboard"
'GameScene' does not have a member named 'showViewController'

Can anybody please explain why this does not work, and also please post a working solution?

Thanks so much in advance!


回答1:


This is because the game scene does not have a property called storyboard or showViewController. These are part of the UIViewController class.
. To access them inside GameScene you can create a property inside the GameScene pointing to the current UIViewController.

class GameScene: SKScene {
    var gameViewController : UIViewController!
}

You can assign the property inside the GameViewController class.

override func viewDidLoad() {
    super.viewDidLoad()

    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {

        // Configure the view code

        scene.gameViewController = self // Added line

        skView.presentScene(scene)
    }
}

Then you can use it inside GameScene like this.

let vc : AnyObject! = self.gameViewController.storyboard!.instantiateViewControllerWithIdentifier("main")
self.gameViewController.showViewController(vc as! UIViewController, sender: vc)


来源:https://stackoverflow.com/questions/30228212/instantiate-a-game-scene-view-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!