Beginning Storyboards in iOS 5 Part 2

Ray Wenderlich

Serve yourself with some Storyboards!

Note from Ray: This is the third iOS 5 tutorial in the iOS 5 Feast! This tutorial is a free preview chapter from our new book iOS 5 By Tutorials. Matthijs Hollemans wrote this chapter – the same guy who wrote the iOS Apprentice Series. Enjoy!

This is a post by iOS Tutorial Team member Matthijs Hollemans, an experienced iOS developer and designer.

If you want to learn more about the new storyboarding feature in iOS 5, you’ve come to the right place!

In the first part of the tutorial series, we covered the basics of using the new storyboard editor to create and connect various view controllers, along with how to make custom table view cells directly from the storyboard editor.

In this second and final part of the tutorial series, we’ll cover segues, static table view cells, the add player screen, and a game picker screen!

We’ll start where we left off last tutorial, so open your project from last time, or go through the previous tutorial first.

OK, let’s dive into some of the other cool new features in Storyboarding!

Introducing Segues

It’s time to add more view controllers to our storyboard. We’re going to create a screen that allows users to add new players to the app.

Drag a Bar Button Item into the right slot of the navigation bar on the Players screen. In the Attributes Inspector change its Identifier to Add to make it a standard + button. When you tap this button we’ll make a new modal screen pop up that lets you enter the details for a new player.

Drag a new Table View Controller into the canvas, to the right of the Players screen. Remember that you can double-click the canvas to zoom out so you have more room to work with.

Keep the new Table View Controller selected and embed it in a Navigation Controller (in case you forgot, from the menubar pick Editor\Embed In\Navigation Controller).

Here’s the trick: Select the + button that we just added on the Players screen and ctrl-drag to the new Navigation Controller:

Creating a segue in the storyboard editor

Release the mouse button and a small popup menu shows up:

Popup to choose Segue type - push, modal, or custom

Choose Modal. This places a new arrow between the Players screen and the Navigation Controller:

A new segue in the storyboard editor

This type of connection is known as a segue (pronounce: seg-way) and represents a transition from one screen to another. The connections we had so far were relationships and they described one view controller containing another. A segue, on the other hand, changes what is on the screen. They are triggered by taps on buttons, table view cells, gestures, and so on.

The cool thing about using segues is that you no longer have to write any code to present the new screen, nor do you have to hook up your buttons to IBActions. What we just did, dragging from the Bar Button Item to the next screen, is enough to create the transition. (If your control already had an IBAction connection, then the segue overrides that.)

Run the app and press the + button. A new table view will slide up the screen!

App with modal segue

This is a so-called “modal” segue. The new screen completely obscures the previous one. The user cannot interact with the underlying screen until they close the modal screen first. Later on we’ll also see “push” segues that push new screens on the navigation stack.

The new screen isn’t very useful yet — you can’t even close it to go back to the main screen!

Segues only go one way, from the Players screen to this new one. To go back, we have to use the delegate pattern. For that, we first have to give this new scene its own class. Add a new UITableViewController subclass to the project and name it PlayerDetailsViewController.

To hook it up to the storyboard, switch back to MainStoryboard.storyboard, select the new Table View Controller scene and in the Identity Inspector set its Class to PlayerDetailsViewController. I always forget this very important step, so to make sure you don’t, I’ll keep pointing it out.

While we’re there, change the title of the screen to “Add Player” (by double-clicking in the navigation bar). Also add two Bar Button Items to the navigation bar. In the Attributes Inspector, set the Identifier of the button to the left to Cancel, and the one on the right Done.

Setting the title of the navigation bar to "Add Player"

Then change PlayerDetailsViewController.h to the following:

@class PlayerDetailsViewController;
 
@protocol PlayerDetailsViewControllerDelegate <NSObject>
- (void)playerDetailsViewControllerDidCancel:
  (PlayerDetailsViewController *)controller;
- (void)playerDetailsViewControllerDidSave:
  (PlayerDetailsViewController *)controller;
@end
 
@interface PlayerDetailsViewController : UITableViewController
 
@property (nonatomic, weak) id <PlayerDetailsViewControllerDelegate> delegate;
 
- (IBAction)cancel:(id)sender;
- (IBAction)done:(id)sender;
 
@end

This defines a new delegate protocol that we’ll use to communicate back from the Add Player screen to the main Players screen when the user taps Cancel or Done.

Switch back to the Storyboard Editor, and hook up the Cancel and Done buttons to their respective action methods. One way to do this is to ctrl-drag from the bar button to the view controller and then picking the correct action name from the popup menu:

Connecting the action of a bar button item to the view controller in the storyboard editor

In PlayerDetailsViewController.m, add the following two methods at the bottom of the file:

- (IBAction)cancel:(id)sender
{
	[self.delegate playerDetailsViewControllerDidCancel:self];
}
- (IBAction)done:(id)sender
{
	[self.delegate playerDetailsViewControllerDidSave:self];
}

These are the action methods for the two bar buttons. For now, they simply let the delegate know what just happened. It’s up to the delegate to actually close the screen. (That is not a requirement, but that’s how I like to do it. Alternatively, you could make the Add Player screen close itself before or after it has notified the delegate.)

Note that it is customary for delegate methods to include a reference to the object in question as their first (or only) parameter, in this case the PlayerDetailsViewController. That way the delegate always knows which object sent the message.

Don’t forget to synthesize the delegate property:

@synthesize delegate;

Now that we’ve given the PlayerDetailsViewController a delegate protocol, we still need to implement that protocol somewhere. Obviously, that will be in PlayersViewController since that is the view controller that presents the Add Player screen. Add the following to PlayersViewController.h:

#import "PlayerDetailsViewController.h"
 
@interface PlayersViewController : UITableViewController <PlayerDetailsViewControllerDelegate>

And to the end of PlayersViewController.m:

#pragma mark - PlayerDetailsViewControllerDelegate
 
- (void)playerDetailsViewControllerDidCancel:
  (PlayerDetailsViewController *)controller
{
	[self dismissViewControllerAnimated:YES completion:nil];
}
 
- (void)playerDetailsViewControllerDidSave:
  (PlayerDetailsViewController *)controller
{
	[self dismissViewControllerAnimated:YES completion:nil];
}

Currently these delegate methods simply close the screen. Later we’ll make them do more interesting things.

The dismissViewControllerAnimated:completion: method is new in iOS 5. You may have used dismissModalViewControllerAnimated: before. That method still works but the new version is the preferred way to dismiss view controllers from now on (it also gives you the ability to execute additional code after the screen has been dismissed).

There is only one thing left to do to make all of this work: the Players screen has to tell the PlayerDetailsViewController that it is now its delegate. That seems like something you could set up in the Storyboard Editor just by dragging a line between the two. Unfortunately, that is not possible. To pass data to the new view controller during a segue, we still need to write some code.

Add the following method to PlayersViewController (it doesn’t really matter where):

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"AddPlayer"])
	{
		UINavigationController *navigationController = 
          segue.destinationViewController;
		PlayerDetailsViewController 
          *playerDetailsViewController = 
            [[navigationController viewControllers] 
              objectAtIndex:0];
		playerDetailsViewController.delegate = self;
	}
}

The prepareForSegue method is invoked whenever a segue is about to take place. The new view controller has been loaded from the storyboard at this point but it’s not visible yet, and we can use this opportunity to send data to it. (You never call prepareForSegue yourself, it’s a message from UIKit to let you know that a segue has just been triggered.)

Note that the destination of the segue is the Navigation Controller, because that is what we connected to the Bar Button Item. To get the PlayerDetailsViewController instance, we have to dig through the Navigation Controller’s viewControllers property to find it.

Run the app, press the + button, and try to close the Add Player screen. It still doesn’t work!

That’s because we never gave the segue an identifier. The code from prepareForSegue checks for that identifier (“AddPlayer”). It is recommended to always do such a check because you may have multiple outgoing segues from one view controller and you’ll need to be able to distinguish between them (something that we’ll do later in this tutorial).

To fix this issue, go into the Storyboard Editor and click on the segue between the Players screen and the Navigation Controller. Notice that the Bar Button Item now lights up, so you can easily see which control triggers this segue.

In the Attributes Inspector, set Identifier to “AddPlayer”:

Setting the segue identifier

If you run the app again, tapping Cancel or Done will now properly close the screen and return you to the list of players.

Note: It is perfectly possible to call dismissViewControllerAnimated:completion: from the modal screen. There is no requirement that says this must be done by the delegate. I personally prefer to let the delegate to this but if you want the modal screen to close itself, then go right ahead. There’s one thing you should be aware of: If you previously used [self.parentViewController dismissModalViewControllerAnimated:YES] to close the screen, then that may no longer work. Instead of using self.parentViewController, simply call the method on self or on self.presentingViewController, which is a new property that was introduced with iOS 5.

By the way, the Attributes Inspector for the segue also has a Transition field. You can choose different animations:

Setting the transition style for a segue

Play with them to see which one you like best. Don’t change the Style setting, though. For this screen it should be Modal — any other option will crash the app!

We’ll be using the delegate pattern a few more times in this tutorial. Here’s a handy checklist for setting up the connections between two scenes:

  1. Create a segue from a button or other control on the source scene to the destination scene. (If you’re presenting the new screen modally, then often the destination will be a Navigation Controller.)
  2. Give the segue a unique Identifier. (It only has to be unique in the source scene; different scenes can use the same identifier.)
  3. Create a delegate protocol for the destination scene.
  4. Call the delegate methods from the Cancel and Done buttons, and at any other point your destination scene needs to communicate with the source scene.
  5. Make the source scene implement the delegate protocol. It should dismiss the destination view controller when Cancel or Done is pressed.
  6. Implement prepareForSegue in the source view controller and do destination.delegate = self;.

Delegates are necessary because there is no such thing as a reverse segue. When a segue is triggered it always creates a new instance of the destination view controller. You can certainly make a segue back from the destination to the source, but that may not do what you expect.

If you were to make a segue back from the Cancel button to the Players screen, for example, then that wouldn’t close the Add Player screen and return to Players, but it creates a new instance of the Players screen. You’ve started an infinite cycle that only ends when the app runs out of memory.

Remember: Segues only go one way, they are only used to open a new screen. To go back you dismiss the screen (or pop it from the navigation stack), usually from a delegate. The segue is employed by the source controller only, the destination view controller doesn’t even know that it was invoked by a segue.

Static Cells

When we’re finished, the Add Player screen will look like this:

The finished add Player screen

That’s a grouped table view, of course, but the new thing is that we don’t have to create a data source for this table. We can design it directly in the Storyboard Editor, no need to write cellForRowAtIndexPath for this one. The new feature that makes this possible is static cells.

Select the table view in the Add Player screen and in the Attributes Inspector change Content to Static Cells. Set Style to Grouped and Sections to 2.

Configuring a table view to use static cells in the storyboard editor

When you change the value of the Sections attribute, the editor will clone the existing section. (You can also select a specific section in the Document Outline on the left and duplicate it.)

Our screen will have only one row in each section, so select the superfluous cells and delete them.

Select the top-most section. In its Attributes Inspector, give the Header field the value “Player Name”.

Setting the section header for a table view

Drag a new Text Field into the cell for this section. Remove its border so you can’t see where the text field begins or ends. Set the Font to System 17 and uncheck Adjust to Fit.

We’re going to make an outlet for this text field on the PlayerDetailsViewController using the Assistant Editor feature of Xcode. Open the Assistant Editor with the button from the toolbar (the one that looks like a tuxedo / alien face). It should automatically open on PlayerDetailsViewController.h.

Select the text field and ctrl-drag into the .h file:

Ctrl-dragging to connect to an outlet in the assistant editor

Let go of the mouse button and a popup appears:

The popup that shows when you connect a UITextField to an outlet

Name the new outlet nameTextField. After you click Connect, Xcode will add the following property to PlayerDetailsViewController.h:

@property (strong, nonatomic) IBOutlet UITextField *nameTextField;

It has also automatically synthesized this property and added it to the viewDidUnload method in the .m file.

This is exactly the kind of thing I said you shouldn’t try with prototype cells, but for static cells it is OK. There will be only one instance of each static cell (unlike prototype cells, they are never copied) and so it’s perfectly acceptable to connect their subviews to outlets on the view controller.

Set the Style of the static cell in the second section to Right Detail. This gives us a standard cell style to work with. Change the label on the left to read “Game” and give the cell a disclosure indicator accessory. Make an outlet for the label on the right (the one that says “Detail”) and name it detailLabel. The labels on this cell are just regular UILabel objects.

The final design of the Add Player screen looks like this:

The final design of the Add Player screen

When you use static cells, your table view controller doesn’t need a data source. Because we used an Xcode template to create our PlayerDetailsViewController class, it still has some placeholder code for the data source, so let’s remove that code now that we have no use for it. Delete anything between the:

#pragma mark - Table view data source

and the:

#pragma mark - Table view delegate

lines. That should silence Xcode about the warnings it has been giving us ever since we added this class.

Run the app and check out our new screen with the static cells. All without writing a line of code — in fact, we threw away a bunch of code!

We can’t avoid writing code altogether, though. When you added the text field to the first cell, you probably noticed it didn’t fit completely, there is a small margin of space around the text field. The user can’t see where the text field begins or ends, so if they tap in the margin and the keyboard doesn’t appear, they’ll be confused. To avoid that, we should let a tap anywhere in that row bring up the keyboard. That’s pretty easy to do, just add replace the tableView:didSelectRowAtIndexPath method with the following:

- (void)tableView:(UITableView *)tableView 
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 0)
		[self.nameTextField becomeFirstResponder];
}

This just says that if the user tapped in the first cell we activate the text field (there is only one cell in the section so we’ll just test for the section index). This will automatically bring up the keyboard. It’s just a little tweak, but one that can save users a bit of frustration.

You should also set the Selection Style for the cell to None (instead of Blue) in the Attributes Inspector, otherwise the row becomes blue if the user taps in the margin around the text field.

All right, that’s the design of the Add Player screen. Now let’s actually make it work.

The Add Player Screen at Work

For now we’ll ignore the Game row and just let users enter the name of the player, nothing more.

When the user presses the Cancel button the screen should close and whatever data they entered will be lost. That part already works. The delegate (the Players screen) receives the “did cancel” message and simply dismisses the view controller.

When the user presses Done, however, we should create a new Player object and fill in its properties. Then we should tell the delegate that we’ve added a new player, so it can update its own screen.

So inside PlayerDetailsViewController.m, change the done method to:

- (IBAction)done:(id)sender
{
	Player *player = [[Player alloc] init];
	player.name = self.nameTextField.text;
	player.game = @"Chess";
	player.rating = 1;
	[self.delegate playerDetailsViewController:self   
     didAddPlayer:player];
}

This requires an import for Player:

#import "Player.h"

The done method now creates a new Player instance and sends it to the delegate. The delegate protocol currently doesn’t have this method, so change its definition in PlayerDetailsViewController.h file to:

@class Player;
 
@protocol PlayerDetailsViewControllerDelegate <NSObject>
- (void)playerDetailsViewControllerDidCancel:
  (PlayerDetailsViewController *)controller;
- (void)playerDetailsViewController:
  (PlayerDetailsViewController *)controller 
  didAddPlayer:(Player *)player;
@end

The “didSave” method declaration is gone. Instead, we now have “didAddPlayer”.

The last thing to do is to add the implementation for this method in PlayersViewController.m:

 
- (void)playerDetailsViewController:
  (PlayerDetailsViewController *)controller 
  didAddPlayer:(Player *)player
{
	[self.players addObject:player];
	NSIndexPath *indexPath = 
     [NSIndexPath indexPathForRow:[self.players count] - 1 
       inSection:0];
	[self.tableView insertRowsAtIndexPaths:
      [NSArray arrayWithObject:indexPath] 
       withRowAnimation:UITableViewRowAnimationAutomatic];
	[self dismissViewControllerAnimated:YES completion:nil];
}

This first adds the new Player object to the array of players. Then it tells the table view that a new row was added (at the bottom), because the table view and its data source must always be in sync. We could have just done a [self.tableView reloadData] but it looks nicer to insert the new row with an animation. UITableViewRowAnimationAutomatic is a new constant in iOS 5 that automatically picks the proper animation, depending on where you insert the new row, very handy.

Try it out, you should now be able to add new players to the list!

If you’re wondering about performance of these storyboards, then you should know that loading a whole storyboard at once isn’t a big deal. The Storyboard doesn’t instantiate all the view controllers right away, only the initial view controller. Because our initial view controller is a Tab Bar Controller, the two view controllers that it contains are also loaded (the Players scene and the scene from the second tab).

The other view controllers are not instantiated until you segue to them. When you close these view controllers they are deallocated again, so only the actively used view controllers are in memory, just as if you were using separate nibs.

Let’s see that in practice. Add the following methods to PlayerDetailsViewController.m:

- (id)initWithCoder:(NSCoder *)aDecoder
{
	if ((self = [super initWithCoder:aDecoder]))
	{
		NSLog(@"init PlayerDetailsViewController");
	}
	return self;
}
- (void)dealloc
{
	NSLog(@"dealloc PlayerDetailsViewController");
}

We’re overriding the initWithCoder and dealloc methods and making them log a message to the Debug Area. Now run the app again and open the Add Player screen. You should see that this view controller did not get allocated until that point. When you close the Add Player screen, either by pressing Cancel or Done, you should see the NSLog from dealloc. If you open the screen again, you should also see the message from initWithCoder again. This should reassure you that view controllers are loaded on-demand only, just as they would if you were loading nibs by hand.

One more thing about static cells, they only work in UITableViewController. The Storyboard Editor will let you add them to a Table View object inside a regular UIViewController, but this won’t work during runtime. The reason for this is that UITableViewController provides some extra magic to take care of the data source for the static cells. Xcode even prevents you from compiling such a project with the error message: “Illegal Configuration: Static table views are only valid when embedded in UITableViewController instances”.

Prototype cells, on the other hand, work just fine in a regular view controller. Neither work in Interface Builder, though. At the moment, if you want to use prototype cells or static cells, you’ll have to use a storyboard.

It is not unthinkable that you might want to have a single table view that combines both static cells and regular dynamic cells, but this isn’t very well supported by the SDK. If this is something you need to do in your own app, then see here for a possible solution.

Note: If you’re building a screen that has a lot of static cells — more than can fit in the visible frame — then you can scroll through them in the Storyboard Editor with the scroll gesture on the mouse or trackpad (2 finger swipe). This might not be immediately obvious, but it works quite well.

The Game Picker Screen

Tapping the Game row in the Add Player screen should open a new screen that lets the user pick a game from a list. That means we’ll be adding yet another table view controller, although this time we’re going to push it on the navigation stack rather than show it modally.

Drag a new Table View Controller into the storyboard. Select the Game table view cell in the Add Player screen (be sure to select the entire cell, not one of the labels) and ctrl-drag to the new Table View Controller to create a segue between them. Make this a Push segue and give it the identifier “PickGame”.

Double-click the navigation bar and name this new scene “Choose Game”. Set the Style of the prototype cell to Basic, and give it the reuse identifier “GameCell”. That’s all we need to do for the design of this screen:

The design for the Game Picker screen

Add a new UITableViewController subclass file to the project and name it GamePickerViewController. Don’t forget to set the Class of the Table View Controller in the storyboard to link these two.

First we shall give this new screen some data to display. Add a new instance variable to GamePickerViewController.h:

@interface GamePickerViewController : UITableViewController {
    NSArray * games;
}

Then switch to GamePickerViewController.m, and fill up this array in viewDidLoad:

- (void)viewDidLoad
{
	[super viewDidLoad];
	games = [NSArray arrayWithObjects:
             @"Angry Birds",
             @"Chess",
             @"Russian Roulette",
             @"Spin the Bottle",
             @"Texas Hold’em Poker",
             @"Tic-Tac-Toe",
             nil];
}

Because we create this array in viewDidUnload, we have to release it in viewDidUnload:

- (void)viewDidUnload
{
	[super viewDidUnload];
	games = nil;
}

Even though viewDidUnload will never actually be called on this screen (we never obscure it with another view), it’s still good practice to always balance your allocations with releases.

Replace the data source methods from the template with:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView 
  numberOfRowsInSection:(NSInteger)section
{
	return [games count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView 
  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tableView 
     dequeueReusableCellWithIdentifier:@"GameCell"];
	cell.textLabel.text = [games objectAtIndex:indexPath.row];
	return cell;
}

That should do it as far as the data source is concerned. Run the app and tap the Game row. The new Choose Game screen will slide into view. Tapping the rows won’t do anything yet, but because this screen is presented on the navigation stack you can always press the back button to return to the Add Player screen.

App with Choose Game screen

This is pretty cool, huh? We didn’t have to write any code to invoke this new screen. We just dragged from the static table view cell to the new scene and that was it. (Note that the table view delegate method didSelectRowAtIndexPath in PlayerDetailsViewController is still called when you tap the Game row, so make sure you don’t do anything there that will conflict with the segue.)

Of course, this new screen isn’t very useful if it doesn’t send any data back, so we’ll have to add a new delegate for that. Add the following to GamePickerViewController.h:

@class GamePickerViewController;
 
@protocol GamePickerViewControllerDelegate <NSObject>
- (void)gamePickerViewController:
  (GamePickerViewController *)controller 
  didSelectGame:(NSString *)game;
@end
 
@interface GamePickerViewController : UITableViewController
 
@property (nonatomic, weak) id <GamePickerViewControllerDelegate> delegate;
@property (nonatomic, strong) NSString *game;
 
@end

We’ve added a delegate protocol with just one method, and a property that will hold the name of the currently selected game.

Change the top of GamePickerViewController.m to:

@implementation GamePickerViewController
{
	NSArray *games;
	NSUInteger selectedIndex;
}
@synthesize delegate;
@synthesize game;

This adds a new ivar, selectedIndex, and synthesizes the properties.

Then add the following line to the bottom of viewDidLoad:

selectedIndex = [games indexOfObject:self.game];

The name of the selected game will be set in self.game. Here we figure out what the index is for that game in the list of games. We’ll use that index to set a checkmark in the table view cell. For this work, self.game must be filled in before the view is loaded. That will be no problem because we’ll do this in the caller’s prepareForSegue, which takes place before viewDidLoad.

Change cellForRowAtIndexPath to:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tableView 
     dequeueReusableCellWithIdentifier:@"GameCell"];
	cell.textLabel.text = [games objectAtIndex:indexPath.row];
	if (indexPath.row == selectedIndex)
		cell.accessoryType = 
          UITableViewCellAccessoryCheckmark;
	else
		cell.accessoryType = UITableViewCellAccessoryNone;
	return cell;
}

This sets a checkmark on the cell that contains the name of the currently selected game. I’m sure this small gesture will be appreciated by the users of the app.

Replace the placeholder didSelectRowAtIndexPath method from the template with:

- (void)tableView:(UITableView *)tableView 
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if (selectedIndex != NSNotFound)
	{
		UITableViewCell *cell = [tableView 
          cellForRowAtIndexPath:[NSIndexPath 
            indexPathForRow:selectedIndex inSection:0]];
		cell.accessoryType = UITableViewCellAccessoryNone;
	}
	selectedIndex = indexPath.row;
	UITableViewCell *cell = 
     [tableView cellForRowAtIndexPath:indexPath];
	cell.accessoryType = UITableViewCellAccessoryCheckmark;
	NSString *theGame = [games objectAtIndex:indexPath.row];
	[self.delegate gamePickerViewController:self 
     didSelectGame:theGame];
}

First we deselect the row after it was tapped. That makes it fade from the blue highlight color back to the regular white. Then we remove the checkmark from the cell that was previously selected, and put it on the row that was just tapped. Finally, we return the name of the chosen game to the delegate.

Run the app now to test that this works. Tap the name of a game and its row will get a checkmark. Tap the name of another game and the checkmark moves along with it. The screen ought to close as soon as you tap a row but that doesn’t happen yet because we haven’t actually hooked up the delegate.

In PlayerDetailsViewController.h, add an import:

#import "GamePickerViewController.h"

And add the delegate protocol to the @interface line:

@interface PlayerDetailsViewController : UITableViewController <GamePickerViewControllerDelegate>

In PlayerDetailsViewController.m, add the prepareForSegue method:

 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"PickGame"])
	{
		GamePickerViewController *gamePickerViewController = 
          segue.destinationViewController;
		gamePickerViewController.delegate = self;
		gamePickerViewController.game = game;
	}
}

This is similar to what we did before. This time the destination view controller is the game picker screen. Remember that this happens after GamePickerViewController is instantiated but before its view is loaded.

The “game” variable is new. This is a new instance variable:

@implementation PlayerDetailsViewController
{
	NSString *game;
}

We use this ivar to remember the selected game so we can store it in the Player object later. We should give it a default value. The initWithCoder method is a good place for that:

- (id)initWithCoder:(NSCoder *)aDecoder
{
	if ((self = [super initWithCoder:aDecoder]))
	{
		NSLog(@"init PlayerDetailsViewController");
		game = @"Chess";
	}
	return self;
}

If you’ve worked with nibs before, then initWithCoder will be familiar. That part has stayed the same with storyboards; initWithCoder, awakeFromNib, and viewDidLoad are still the methods to use. You can think of a storyboard as a collection of nibs with additional information about the transitions and relationships between them. But the views and view controllers inside the storyboard are still encoded and decoded in the same way.

Change viewDidLoad to display the name of the game in the cell:

- (void)viewDidLoad
{
	[super viewDidLoad];
	self.detailLabel.text = game;
}

All that remains is to implement the delegate method:

#pragma mark - GamePickerViewControllerDelegate
 
- (void)gamePickerViewController:
  (GamePickerViewController *)controller 
  didSelectGame:(NSString *)theGame
{
	game = theGame;
	self.detailLabel.text = game;
	[self.navigationController popViewControllerAnimated:YES];
}

This is pretty straightforward, we put the name of the new game into our game ivar and the cell’s label, and then we close the Choose Game screen. Because it’s a push segue, we have to pop this screen off the navigation stack to close it.

Our done method can now put the name of the chosen game into the new Player object:

- (IBAction)done:(id)sender
{
	Player *player = [[Player alloc] init];
	player.name = self.nameTextField.text;
	player.game = game;
	player.rating = 1;
	[self.delegate playerDetailsViewController:self didAddPlayer:player];
}

Awesome, we now have a functioning Choose Game screen!

Choose Game screen with checkmark

Where To Go From Here?

Here is a example project with all of the code from the above tutorial.

Congratulations, you now know the basics of using the Storyboard Editor, and can create apps with multiple view controllers transitioning between each other with segues!

If you want to learn more about Storyboards in iOS 5, check out our new book iOS 5 By Tutorials. It includes another entire chapter on “Intermediate Storyboards” where we cover:

  • How to change the PlayerDetailsViewController so that it can also edit existing Player objects.
  • How to have multiple outgoing segues to other scenes, and how to make your view controllers re-usable so they can handle multiple incoming segues.
  • How to perform segues from disclosure buttons, gestures, and any other event you can think of.
  • How to make custom segues – you don’t have to be limited to the standard Push and Modal animations!
  • How to use storyboards on the iPad, with a split-view controller and popovers.
  • And finally, how to manually load storyboards and using more than one storyboard inside an app.

If you have any questions or comments on this tutorial or on storyboarding in iOS 5 in general, please join the forum discussion below!

Matthijs Hollemans

This is a post by iOS Tutorial Team member Matthijs Hollemans, an experienced iOS developer and designer.

Ray Wenderlich

Ray is an indie software developer currently focusing on iPhone and iPad development, and the administrator of this site. He’s the founder of a small iPhone development studio called Razeware, and is passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

User Comments

162 Comments

[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ]
  • I don't think it has something to do with the connections in IB.

    One important thing I forgot to mention is that the app used to work just fine as it was.
    But because I am not too familiar with the initWithCoder method I removed the line
    game = @"Chess";
    from that method:
    Code: Select all
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
       if ((self = [super initWithCoder:aDecoder]))
       {
          NSLog(@"init PlayerDetailsViewController");
          // game = @"Chess";
       }
       return self;
    }

    And that's when the problem occurred.
    As far as I have understood the concept that method is called once after the segue from the PlayersViewController to the PlayerDetailsViewController has been triggered. Because when adding a new player no game has been chosen yet you kind of preselect the game "Chess" so that the view is consistent and the detailLabel shows a game at any given time.

    So I thought when removing that line from the code the detailLabel won't show anything the first time I see the PlayerDetaislViewController screen, but the rest of its behaviour would not be changed. But the strange thing is: By removing that one particular "initializing" line of code the detailLabel suddenly shows the behaviour mentioned in my previous post. :o
    phijay
  • @phijay What does it do if you do this:

    Code: Select all
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
       if ((self = [super initWithCoder:aDecoder]))
       {
          NSLog(@"init PlayerDetailsViewController");
          game = @"";
       }
       return self;
    }


    So you set game to @"" instead of @"Chess". Does that make a difference?
    Hollance
  • Hi Hollance,

    Code: Select all
    game = @"";

    has the same effect as
    Code: Select all
    // game = @"Chess";

    i.e. deleting the row.

    I also observed the following:
    When clicking the game row the first time, the GamePickerViewController appears, I select a game, the window returns to the PlayerDetailsViewController with no effect. The detailLabel does not show anything.
    But when clicking the game row the second time, just when the PlayerDetailsViewController slides to the left and gets covered by the GamePickerViewController due to the animation, there is a short moment where the detailLabel suddenly shows the previously selected game. So when clicking the detailLabel to choose a game for the second time it suddenly "remembers" that it was supposed to show the game. :?
    phijay
  • Odd. The only time I have seen table view cells draw funny like that is when people connect the wrong outlets to the wrong labels, but that shouldn't apply here because you're using one of the built-in cell styles.
    Hollance
  • Awesome. The part about delegates with storyboards (the prepareForSegue stuff) was exactly what I needed. Lots of outdated Q&As on that stuff around SO and the web. Helped me solve my problem! ;)
    kmc239
  • Hi:

    This is great! I could complete Part 1 and Part 2 just following the description. But I have found that it doesn't work for the users' data such as adding names, changing ranks, and etc. How can we save all the data that the users handle / customize?

    Thanks.
    ringo
  • I am having trouble with understanding how to pass information from one page to another, especially with regards to view controllers. For example, I tried adding a View Controller as the entry point of the program, created a button on the page, and added a segue from the button to the tab bar controller. I could not figure out how to correctly link the two pages in AppDelegate, so my table view is now empty. How would I go about doing this?
    joresnik
  • You don't have to use delegate,just use "- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion " method on the presented view controller,it automatically forwards the message to the presenting view controller.
    PerryLee
  • Great tutorial, i have the book.

    Now when i started to implement the tutorial for my own app, i got stuck at the following:

    basically the add player TVC, i set 2 sections, 1 section with 2 static cells without textfield and type rightdetail same as your gamepicker, second section1 cell for UIDatePicker.

    In the first section both cells will segue to the gamepickerTVC but different segue identifiers, the first cell segue works fine and updates the detailLabel text, now I want the second cell to segue to the gamePicekTVC and update its detaillabel.text, the segue works fine but didn`t update the cell label on didselectRow.

    Any idea on how I can build an if statement in this:
    - (void)gamePickerViewController:(GamePickerViewController *)controller didSelectGame:(NSString *)theGame

    to pass the correct selected row to the cell which initiated the segue?

    Thanks
    kupilot
  • I worked through this entire tutorial and everything works fine up until the last feature addition. When I tap a game in the Choose Game view, it removes the checkmark from the previous game and adds it to the current game, but nothing else. The didSelectGame method never gets called, so the view never gets popped and the game I selected doesn't get updated in the Players list.

    Any ideas where I went wrong?

    ---- EDIT ----

    I figured it out. I set the identifier "PickGame" on the Game-Details Table View Cell instead of the segue.

    Thanks for the great tutorials! They are very helpful!
    bwhite
  • Why the IBOutlet and IBAction are not visible in ViewController if i do like this
    1) declare IBOutlet and IBAction in .h file
    2) Go to main.storyboard
    3) check for these iboutlet and ibactions in viewcontroller

    in .nib / .xib file its visible then why its not visible in storyboard
    arunjaiswal
  • arunjaiswal wrote:Why the IBOutlet and IBAction are not visible in ViewController if i do like this

    Did you set the Class of the view controller in the Identity Inspector to the name of your view controller?
    Hollance
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ]

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Vote for Our Next Tutorial!

Every week, we alternate between Gaming and Non-Gaming tutorial votes. This week: Gaming!

    Loading ... Loading ...

Last week's winner: Apple TestFlight Tutorial.

Suggest a Tutorial - Past Results

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in January: WatchKit.

Sign Up - January

Our Books

Our Team

Tutorial Team

  • Matt Luedke

... 60 total!

Update Team

  • Riccardo D'Antoni
  • Zouhair Mahieddine

... 12 total!

Editorial Team

  • Alexis Gallagher

... 17 total!

Code Team

  • Orta Therox

... 3 total!

Subject Matter Experts

  • Richard Casey

... 4 total!