C. Wagner C. Wagner - 1 year ago 56
Swift Question

Segue only working once?

Hi I made a game using SpriteKit and wanted to add a leaderboard using a

. My segues are working perfectly from my GameViewController to the TableViewController and back. However I can only do this once. Once I am back to my GameViewController, tapping the same button wont take me to the TableViewController for the second time. Why is this happening?

I set it up so when a certain
is tapped it segues to the the TableViewController. Currently I am using this line of code to segue from the
to the
(This code is within GameScene.swift)

self.view!.window!.rootViewController!.performSegueWithIdentifier("showScores", sender: self)

I then setup a Back button within a navigation bar and created a segue back to the GameViewController (by dragging the
to the GameViewController and selecting
). Some help would be appreciated. Thanks!

Answer Source

I think you are segueing to the leaderboard, segueing back, but in the process adding the main game view to the stack rather than removing the leaderboard, so when you try to segue again, it is not the visible game scene that receives the call.

Try using this rather than a segue in your leaderboard code (where you ask to segue back to the game scene):

self.dismissViewControllerAnimated(true, completion: nil)

If that doesn't work use a delegate to ask the game scene to dismiss the leaderboard.

Edit: I was rambling and maxed out my word count for the comment, so thought I'd add my explanation here!

Think of the stack as a pile of paper, where each piece of paper is a viewController, the topmost piece being the one that's visible (naturally). When you segue or present a viewController modally you are adding a viewController to the stack or 'adding a piece of paper to your pile'. It is generally then a bad idea to segue to and from like you were doing because you are adding more and more 'pieces of paper' to the stack. You tend to get memory problems and/or irritating bugs :P. Instead what is considered best practice for programmatically going back is to do one of two things: if you are using a navigationController you should call popViewControllerAnimated, or if you aren't, like in this case, you should use dismissViewControllerAnimated. Both these functions take the topmost 'piece of paper' off the stack entirely. Fixing that problem of continually adding the viewControllers to the stack. If any of that was confusing (I'm writing this on my phone so could be!) just send me a comment or a message and I'll try to explain better! :)