我有一个带有按钮开始游戏的游戏菜单:
@IBAction func startGame(_ sender: AnyObject) {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "gameViewController") as? GameViewController {
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true, completion: nil)
}
}
游戏结束代码:
if lifes == 0 {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainMenuViewController") as? MainMenuViewController {
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true, completion: nil)
}
}
当用户单击按钮时,我会显示带有 Sprite Kit 场景的新 View Controller 。但是当游戏结束时我回到菜单。如果我们再次点击开始游戏,fps 会从 60(在我的例子中)下降到 30,然后再次下降到 20 等等。看起来旧的 View Controller 仍然有效。如何消除它?
我读过类似的问题,但没有找到答案。
最佳答案
好的,现在你的问题已经清楚了。
当游戏结束时,您不应该呈现新的MainViewController
。这将导致您可能出现无限的 View Controller 堆栈,如下所示:
主要 -> 游戏 -> 主要 -> 游戏 -> ...
相反,您应该关闭 Game vc 并返回到前一个 Controller ,以便内存中始终有一个或两个 Controller 。
所以你应该替换它:
if lifes == 0 {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainMenuViewController") as? MainMenuViewController {
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true, completion: nil)
}
}
这样:
if lifes == 0 {
dismiss(animated: true, completion: nil) //will bring you to previous Main vc
}
编辑:
如果您有两个以上的 Controller 要显示,您应该考虑导航 Controller 方法。基本上你用 rootViewController (MainVC) 创建它,然后推送 GameVC,然后推送 GameOver。
在MainVC中:
self.navigationController?.pushViewController(gameVC, animated: true)
在 GameVC 中:
self.navigationController?.pushViewController(gameOverVC, animated: true)
仅弹出一个 Controller :
self.navigationController?.popViewController(animated: true)
弹出到第一个 Controller :
self.navigationController?.popToRootViewController(animated: true)
关于ios - 将 ViewController 与场景一起呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40148433/