6.2. Passing Data from One Screen to Another

Problem

You want to pass data from one scene to another using storyboards.

Solution

Use segue objects.

Discussion

A segue is an object, just like any other object in Objective-C. To carry out a transition from one scene to another, the storyboard runtime creates a segue object for that transition. A segue is an instance of class UIStoryboardSegue. To start a transition, the current view controller (which will get pushed out of the screen after the segue) receives the prepareForSegue:sender: message, where the prepareForSegue parameter will be an object of type UIStoryboardSegue. If you want to pass any data from the current view controller to the view controller that is about to appear on the screen, you need to do that in the prepareForSegue:sender: method.

Note

For this recipe to make sense, you need to have followed the instructions in Recipe 6.1 and created two view controllers inside a navigation controller on your storyboard.

Let’s have a look at a real-life example of using segues. In this recipe, we are going to display a view controller similar to that shown in Figure 6-4.

Whatever the user places in our text field will get passed to the second view controller through a segue and will get set as the title of that view controller. The second view controller’s canvas will be empty. So using the technique that you learned in Recipe 6.1, place your first view controller inside a navigation controller. Now place another view controller from ...

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.