问题
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