cha*_*has 7 xcode ios segue sprite-kit swift
我正在使用SpriteKit在Xcode 8中制作一个游戏,并且在编程上触发segue时非常困难.我已经进入"Main.storyboard"并在我的"GameViewController"和"MenuViewController"之间制作了一个segue,因为它标识符为"toMenu".
尝试失败#1
在我的GameScene.swift文件中,我将以下代码添加到更新功能中.
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if gameIsRunning == false{
score = 0
performSegue(withIdentifier: "toMenu", sender: self)
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是每当gameIsRunning为false时触发segue.但是,我收到以下错误:
Use of unresolved identifier 'performSegue'
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为performSegue是根据API Reference的声明.
尝试失败#2
我通过将以下代码放入"GameScene.swift"来尝试此解决方案
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if gameIsRunning == false{
score = 0
GameScene(MenuViewController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误:
Type of expression is ambiguous without more context
Run Code Online (Sandbox Code Playgroud)
尝试失败#3
我发现这个解决方案非常令人困惑,但无论如何我都在追随.我已经完成了第1步,所以如第2步所述,我将以下代码放在"GameViewController.swift"的底部
func goToDifferentView() {
self.performSegue(withIdentifier: "toMenu", sender: self)
}
Run Code Online (Sandbox Code Playgroud)
并没有得到错误!然后我按照解决方案的第3步中的说明将此代码添加到"GameViewController.swift"
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "toMenu"), object: nil)
Run Code Online (Sandbox Code Playgroud)
然后我做了解决方案的第4步,所以我将以下代码放入"MenuViewController.swift"
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "toMenu"), object: nil) as Notification)
Run Code Online (Sandbox Code Playgroud)
然后我将以下代码放入我的"GameScene.swift"文件中以实际调用该函数.
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if gameIsRunning == false{
score = 0
GameViewController().goToDifferentView()
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的iPhone上运行我的游戏,一切顺利,直到我进入游戏的部分,其中gameIsRunning变为假.而不是segue做它的事情,我得到以下错误:
Thread 1: Signal SIGABRT
Run Code Online (Sandbox Code Playgroud)
我已经多次得到这个错误,而且我总是在"Main.storyboard"中错误地连接了一些东西.然而,这是一个非常简单的游戏,一切看起来很正常.在添加我刚刚向您展示的代码之前,我也没有收到此错误.我已多次确认segue具有标识符"toMenu".我完全不知道为什么segue不起作用以及为什么我的Attemp#3导致SIGABRT错误.
由于您试图在 update() 函数中触发此 segue,因此每秒会调用多次。尝试下面的代码,它应该可以工作。
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if gameIsRunning == false{
score = 0
gameIsRunning = true
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "toMenu"), object: nil) as Notification)
}
Run Code Online (Sandbox Code Playgroud)
如果您将print("update")
其放入声明中,if
您就会明白我的意思。在 if 中将 bool设置gameIsRunning
为 true 将确保它只被调用一次。
归档时间: |
|
查看次数: |
163 次 |
最近记录: |