简体   繁体   中英

Dismissing a Game View controller after Performing a Segue to another view controller in Swift

My game looks something like this ----

Main View Controller -> Game View Controller -> Game Score View Controller

Now, After the game is over, I am performing a segue to the Game Score View Controller. But, the Game View Controller is still not dismissed, and since it detects any touch outside the Game View Controller the app crashes. I would appreciate it if anyone could please let me know how can I dismiss the Game View Controller once I perform a segue to the Game Score View Controller? Thanks a lot for the help!

func gameOver() {
    stopGame()
    performSegue(withIdentifier: "2to3segue", sender: self)
}

Edit:

One way to do it would be to pass a reference of GameViewController to GameScoreViewController , and then dismiss the gameVC from it.

In GameViewController :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "2to3segue" {
        let destination = segue.destination as! GameScoreViewController
        destination.gameVC = self
    }
}

Then in GameScoreViewController :

weak var gameVC: GameScoreViewController?

and in ViewDidAppear you dismiss it:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.gameVC?.dismiss(animated: false)
}

Assuming that you're using a NavigationController , you can use this extension in order to remove the GameViewController from the stack after performing your segue:

extension UINavigationController {
    func removeViewController(_ controller: UIViewController.Type) {
        if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {
            viewController.removeFromParent()
        }
    }
}

Then once your performed you segue, you can remove the GameViewController from GameScoreViewController like so:

self.navigationController?.removeViewController(GameViewController.self)

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM