问题
I want to present SKScene
from a UIViewController
in swift language,
I'm developing a game in iOS , the menu is a UIViewController
and the game is in SpriteKit, I need to move from the menu (UIViewController
) to the game (SKScene
) upon pressing a button.
How can I do something like that ?
回答1:
Like @Ron Myschuk said you should consider moving your menu to SpriteKit
. If you want to use UIKit
you will need to communicate the SKScene
with the UIViewController
(I guess that is your problem).
You can achieve this with the delegate pattern.
Using this pattern your code might look something like this:
/// Game actions that should be notified.
Protocol GameSceneDelegate: class {
func gameDidEnd()
}
public class GameScene: SKScene {
weak var gameDelegate: GameSceneDelegate?
// MARK: - Menu Actions
func userDidPressMenuButton() {
///Do what you want to do..
}
}
class GameViewController: UIViewController, GameSceneDelegate{
var scene: GameScene?
override func viewDidLoad() {
if (self.view as! SKView?) != nil {
self.scene = GameScene(fileNamed: "GameScene")
}
self.scene?.gameDelegate = self
}
// MARK: - GameSceneDelegate methods
func gameDidEnd(){
///Do what you want to do..
}
// MARK: - Actions
@IBAction func pressMenuButtonAction(_ sender: Any) {
self.scene?.userDidPressMenuButton()
}
}
When a button is pressed in your UIViewController
you call the SKScene
to do what ever it needs to do. And when the scene needs to tell the menu a relevant action (like game finish) it calls its delegate, that is your UIViewController
.
来源:https://stackoverflow.com/questions/48962880/how-to-move-from-view-controller-to-skscene