How to create an Unwind Segue in iOS 8

The Unwind Segue was introduced in iOS 6 to make retrieving data from a dismissed view controller easier. A regular Segue allows us to send data from one view controller to another, but it’s not easy to bring data back if the user has changed or added details in that view controller. That’s where an Unwind Segue comes in.

Part 1: Code

Here’s how to create one. I’m assuming we have two view controllers at our disposal, ViewController1 has initiated a standard segue, maybe passing some data. The user then changes the data, and upon saving the data, ViewController2 is dismissed and we’re going back to ViewController1.

So in ViewController1 we’ll add a method we can use as an Unwind Segue, which we later hook up in the storyboard to the Exit object. Here’s that method:

- (IBAction)backToTheStart:(UIStoryboardSegue *)segue {
    
    // grab a reference
    ViewController2 *viewController2 = segue.sourceViewController;
    
    // access public properties from ViewController2 here
}

It doesn’t matter what the method is called, just as long as it resides in ViewController1, in which you’ve imported the ViewController2.h file. What DOES matter however that our method is an IBAction and takes a UIStoryboardSegue as a parameter – otherwise Interface builder won’t recognise it, and you won’t be able to drag to the Exit object later.

Meanwhile, in ViewController2, we can make use of the following method which is often provided as a stub in new view controller classes:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    // do any preparation here when the segue is called
}

prepareForSegue is called just before the unwind segue (or any segue for that matter) is about to begin. You may want to read out a text field or any other values and add it to the object or variable that ViewController1 needs access to.

Part 2: Hooking up the Storyboard

With our code in place, control-drag from the button you’d like to use for initiating the segue. You can hook up multiple buttons to the same unwind segue.

Control-drag each button to the Exit object (in ViewController2):

Screen Shot 2015-01-29 at 12.00.49

As soon as the button is pressed, the unwind code in ViewController1 is executed and ViewController2 is dismissed.

Demo Project

I’ve put together a quick demo project on GitHub which is the code I’m creating the screencast above:

Further Reading





Leave a Reply