Arti Arti - 1 month ago 7
Swift Question

Present ViewController with Scene

I have a game menu with button start game:

@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)
}
}


When user click on button i show new view controller with Sprite Kit scene. But when game is over i go back to menu. And if we click Start game again, fps falls from 60(in my case) to 30, then if again to 20 etc. Seems like old view controller still working. How to dismiss it ?

I read similar questions, but didn't find answer in them.

Answer

Ok, now your issue is clear.

You should not present a new MainViewController when game is over. This will lead you to potentially infinite stack of view controllers like this: Main -> Game -> Main -> Game -> ... Instead you should dismiss your Game vc and return to the previous controller, so that you will always have one or two controllers in memory.

So you should replace this:

if lifes == 0 {
    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainMenuViewController") as? MainMenuViewController {
        vc.modalTransitionStyle = .crossDissolve
        self.present(vc, animated: true, completion: nil)
    }
}

With this:

if lifes == 0 {
    dismiss(animated: true, completion: nil) //will bring you to previous Main vc
}

Edit:

If you have more than two controllers to show, you should consider navigation controller approach. Basically you create it with rootViewController (MainVC), then push GameVC, then push GameOver.

In MainVC:

self.navigationController?.pushViewController(gameVC, animated: true)

In GameVC:

self.navigationController?.pushViewController(gameOverVC, animated: true)

To pop only only one controller:

self.navigationController?.popViewController(animated: true)

To pop to the first controller:

self.navigationController?.popToRootViewController(animated: true)
Comments