如何从SKScene中指示使用UIKit创建的视图? [英] How can I indicate a view which has created with UIKit from a SKScene?
问题描述
我有一个名为MainScene.swift的SKScene文件,并在其上创建了一个按钮,供用户跳转到另一个页面。另一个页面不是由SpriteKit创建的,而是由UIKit创建的。在这种情况下,如何指示目标页面和编写代码?
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?
如果我使用SpriteKit创建了两个页面,我通常会在跳转到其他场景时这样做。
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)
}
当我在使用UIKit创建的场景上执行相同的操作时,在Identity列上键入Storyboard ID,然后像这样编码;我只知道使用故事板的方式。
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)
}
}
但是当在创建SKScene和UIKit的场景之间尝试同样的事情时,我不知道如何从前一个场景中指定后者;我不会坚持使用故事板。如果有任何简单的方法,请告诉我。提前谢谢。
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.
推荐答案
这听起来像委托模式的工作。
为LevelScene添加协议;
This sounds like a job for the delegate pattern. Add a protocol for LevelScene;
// LevelScene.swift
protocol LevelScene : class {
var gameDelegate: GameDelegate? { get set }
}
为GameDelegate添加协议;
Add a protocol for GameDelegate;
// GameDelegate.swift
protocol GameDelegate : class {
func gameOver()
}
在你的mainScene中添加协议引用并创建一个名为gameDelegate的属性;
In your mainScene add the protocol reference and create a property called gameDelegate;
class MainScene: SKScene, LevelScene {
weak var gameDelegate: GameDelegate?
}
在你的GameViewController中添加协议参考并实现所需的协议功能 - 在此case就像往常一样叫做gameOver和seque到你的UIKit View;
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)
}
}
在呈现场景时将委托设置为gameViewController;
Set the delegate to gameViewController when presenting the scene;
scene.gameDelegate = self
然后在mainScene中调用委托函数;
Then in mainScene call the delegate function when required;
self.gameDelegate?.gameOver()
这篇关于如何从SKScene中指示使用UIKit创建的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!