Guide to Using Unwind Segues
Unwind segue is a very nice concept in iOS to “go back” to a previous view controller.
There is an Apple Guide to using it, and a good in a nutshell about it.
Here, I will share how I use it in real world applications.
Basics and Pitfalls
You create this method in the view controller which let others unwind to it:
- (IBAction)unwindToHere:(UIStoryboardSegue*)sender {...}
The view controller MUST be present in the navigation hierarchy. Obvious perhaps, but good to note unwind is to “go back”, not jump to anywhere.
- The view controller should have appeared before performing other segues, otherwise you will encounter Warning: Attempt to present on whose view is not in the window hierarchy!
How I use unwind
I always have a FirstViewController
which is the initial view controller on my storyboard.
This FirstViewController
is like a coordinator to other view controllers such as Login, Main, etc..
The advantage of having that is since it is the initial view controller, it will always be in the navigation hierarchy. And thus, it is a good candidate to unwind to (will always succeed!).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
In the example above, I have 2 unwind segues gotoLogin
and gotoMain
. You could have as many unwind segues.
When you add an unwind segue to a scene (read here on how), you could choose gotoLogin
. That is bascially asking to unwind to FirstViewController
, and then asking FirstViewController
to go to Login next.
If it is an unwind operation, the segue is performed right after viewDidAppear
.
If it is not an unwind operation, other logics could be added in viewDidAppear
eg. go to Login if no logged in user.