I am trying to code a hangman game and am having trouble with unwind segues. I have multiple view controllers that all ultimately lead to the same view, where the user plays the actual hangman. However, depending on the presenting controller, I want the game to be in different "modes" (ie: multiplayer, single player, etc.). I am trying to add a play again button that unwinds to the previous view controller, but am unsure how to unwind when there are multiple paths the user could have taken to get to this view.
In other words, my app kind of goes:
A -> B -> C or
A -> D -> C where C can (ideally) unwind to D or B.
I was wondering what the best way to implement this is? Should I just embed all my view controllers in navigation controllers? Or is there a way to present a certain view controller based on a certain condition? Thank you for any help!
If you have any custom logic and want to invoke the unwind segue programmatically to different view controllers, here is how:
Add
unwindFromCViewController
to bothBViewController
andDBViewController
:BViewController.swift
DViewController.swift
In your storyboard, create this segue and give it a identifier, and link it to the action you defined above
unwindFromCViewController
:Invoke the unwind segue from code:
With that, you can unwind to a previous view regardless where it is coming from.
The unwind segue process will generally determine the previous UIViewController instance automatically. The exact process is described in this Tech Note from Apple, but in summary:
So, the precise process will depend on how you presented view controller C - for example, via a modal presentation segue or a push segue on a
UINavigationController
but as long as both B and D implement the unwind action you should be good.I would simply call in code
popViewController:animated
to go to the presenting controller if you pushed it on the navigation stack, ordismissViewController:animated
if it was presented modally.