Beginning Storyboards in iOS 5 Part 2
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 […] By Ray Wenderlich.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Beginning Storyboards in iOS 5 Part 2
35 mins
Static Cells
When we’re finished, the Add Player screen will look like this:
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.
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”.
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:
Let go of the mouse button and a popup appears:
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:
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.