Learn Objective-C: Advanced Tables

In this post we’re going to take a step away from our existing project and look at other things UITableView will allow us to do. We’ll load in data from a plist, add some more elements to our table view, including images, subtexts, and allowing editing. These features allow us and the user to customize table views beyond the default appearance. Table views are a very important part of the iOS SDK and are found in many apps; fortunately, they are easy to customize—you can even create your own cells in anyway you’d like!

Open Xcode and create a new Single View application. Call it “AdvancedTables”, set the class prefix to “AT”, Device Family to iPhone, and Use Automatic Reference Counting. Save the project somewhere and create it.

Next, click here to download a file which contains a list of 51 cities and their population. The file is a basic XML-based plist, which is a file type used throughout iOS to store simple data structures like this. Add the file into the Xcode project.

Setting up the View Controller

Open ATViewController.h and have it adopt UITableViewDelegate and UITableViewDataSource. In ATViewController.xib, drag out a Table View from the Library and place it inside the existing view. Control-Drag from the table back to File’s Owner, connecting the table’s data source and delegate outlets.

Next, go to ATViewController.h. Create two strong properties of type NSMutableArray; call them names and populations. In the .m file, synthesize them. We’ll load in data from the plist in the viewDidLoad method:

  1. - (void)viewDidLoad {
  2.     [super viewDidLoad];
  3.     // Do any additional setup after loading the view, typically from a nib.
  4.     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Cities" ofType:@"plist"];
  5.     NSData *data = [NSData dataWithContentsOfFile:filePath];
  6.     NSPropertyListFormat format;
  7.     NSString *error;
  8.     id fileContents = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
  9.     self.populations = [[fileContents objectForKey:@"City Population"] mutableCopy];
  10.     self.names = [[fileContents objectForKey:@"City Names"] mutableCopy];
  11. }

Notice that we don’t do any sort of checking on the fileContents result. It would may seem like a good idea to at least check if the dictionary had the two keys; if it only had one, the app would crash when trying to access one or both of them. However, this is a special design consideration. The data source is the driving force of the entire app; it wouldn’t make much sense if some of this data doesn’t exist. We don’t really want the app to continue if the data isn’t valid, so letting it crash might be a good idea in this case.

Next, we implement the data source methods like we did in the last post. Our table will only one section; with a more robust data source such as Core Data, it becomes much easier to implement multiple sections and an index down the side like you’d see in the Music app. For now though, we’ll settle for one section. The number of rows will be determined by the number of elements in either one of the data arrays, as they should correspond—and they do!

  1. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  2.     return 1;
  3. }
  5. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  6.     return [self.names count];
  7. }
  9. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  10.     static NSString *cellID = @"CellID";
  11.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
  12.     if (!cell) {        // Create new cell
  13.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
  14.         cell.showsReorderControl = YES;
  15.     }
  16.     cell.textLabel.text = [self.names objectAtIndex:indexPath.row];
  17.     cell.detailTextLabel.text = [NSString stringWithFormat:@"Population: %@", [self.populations objectAtIndex:indexPath.row]];
  18.     cell.imageView.image = [UIImage imageNamed:@"CaliforniaIcon.png"];
  19.     cell.imageView.highlightedImage = [UIImage imageNamed:@"CaliforniaIconPressed.png"];
  20.     return cell;
  21. }

Notably here, we create a cell with a different style, one with a subtitle. The iOS SDK comes with four styles, shown below (click for larger version):


iOS Table View Cell Styles

The default style doesn’t contain any detail text; nothing will happen if you set the detailTextLabel property.

The showsReorderControl property is a boolean; if true, it will display a reordering control that appears in editing mode. We’ll get into that in a little bit.

Adding an Image to Cells

If you want to add an image to the left of the cell (as with album art in the Music app, or video previews in the YouTube app), it takes very little work. Download the icons and add the following lines within the if (!cell) block:

  1. cell.imageView.image = [UIImage imageNamed:@"CaliforniaIcon.png"];
  2. cell.imageView.highlightedImage = [UIImage imageNamed:@"CaliforniaIconPressed.png"];

The image property is what gets displayed normally; the highlightedImage is swapped in if the cell is highlighted.

If you want the image anywhere else in the cell, you’ll have to create your own cells, which will be a topic for another post—there’s a lot involved!

Editing Table Views

First we’ll need some UI to enable editing. Go into the XIB, lower the top margin of the table view, and drag out a normal Navigation Bar and place it at the top of the view, filling the gap. You can have a navigation bar without a nav controller; in that case, it just becomes an “anchor” of sorts for a few commands. You use nav bars at the top of the screen and toolbars at the bottom. Drag out a Bar Button Item and place it on the left of the nav bar; a “well” will appear as you drag over the location. In the Attributes Inspector, set the Title to “Edit”. Connect the button to a new property called editingToggle. In addition, create an outlet for the table view; call it tableView. Wire it up.

Create a new method called toggleEdit and wire it up to the button. First, we’ll set the table’s editing mode to whatever it’s currently not—if it’s not in editing, make it enter editing mode and vice versa. Then we’ll adjust the button to reflect this change in state. In iOS, the Done button has a different tint; we can use a system-defined parameter rather than having to approximate it with our own.

  1. - (IBAction)toggleEdit:(id)sender {
  2.     [self.mainTable setEditing:!self.mainTable.isEditing animated:YES];
  3.     if (self.mainTable.isEditing) {
  4.         [self.editingToggle setStyle:UIBarButtonItemStyleDone];
  5.         [self.editingToggle setTitle:@"Done"];
  6.     }
  7.     else {
  8.         [self.editingToggle setStyle:UIBarButtonItemStyleBordered];
  9.         [self.editingToggle setTitle:@"Edit"];
  10.     }
  11. }

Next we implement a few data source methods to allow editing, then to handle the edits.

  1. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  2.     return YES;
  3. }
  5. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
  6.     return YES;
  7. }
  9. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
  10.     NSUInteger fromRow = [fromIndexPath row];
  11.     NSUInteger toRow = [toIndexPath row];
  12.     id name = [self.names objectAtIndex:fromRow];
  13.     id pop = [self.populations objectAtIndex:fromRow];
  14.     [self.names removeObjectAtIndex:fromRow];
  15.     [self.populations removeObjectAtIndex:fromRow];
  16.     [self.names insertObject:name atIndex:toRow];
  17.     [self.populations insertObject:pop atIndex:toRow];
  18. }
  20. - (void)tableView:(UITableView *)tableView
  21. commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  22.     NSUInteger row = [indexPath row];
  23.     [self.names removeObjectAtIndex:row];
  24.     [self.populations removeObjectAtIndex:row];
  25.     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  26. }

The first two methods tell the table that all the rows can be edited (in this case, deletion is allowed; the alternative is None or Insertion), and that they can be moved. Then we declare the methods that handle the move or delete (in the latter case, it falls under the commitEditingStyle: method). In those methods, we remove (and insert) objects from our backing arrays as necessary.

These edits will remain until the memory is cleared (when the app quits). We’ll look at persistence—saving these changes back to the file—in a later extension.

Other Actions

The UITableViewDelegate declares some methods to support some other actions, including accessory views (views on the side of the cell, which you can wire up to trigger additional actions). Now, we’ll handle the selection, and allow you to put a check mark next to the cell that the user selects.

First, we’ll need to create a new property of type NSIndexPath that will hold the current selection.

  1. @property (strong, nonatomic) NSIndexPath *lastIndexPath;

Next, we need to do some checks in the cellForRow… method—because the method will recycle cells as you scroll, we don’t want the checkmarks to get recycled as well. We check to see if a selection has been made, and if the rows are the same. If they are, then we display the checkmark (this is useful when you scroll back to your selection). Else, we display no checkmark (this is useful if you scroll down or up past your existing selection).

We handle the selection like this:

  1. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  2.     NSUInteger row = indexPath.row;
  3.     NSUInteger oldRow = lastIndexPath.row;
  4.     if (oldRow != row) {
  5.         UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
  6.         newCell.accessoryType = UITableViewCellAccessoryCheckmark;
  7.         UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
  8.         oldCell.accessoryType = UITableViewCellAccessoryNone;
  9.         lastIndexPath = indexPath;
  10.     }
  11.     [tableView deselectRowAtIndexPath:indexPath animated:YES];
  12. }

If the selections are different, we put a checkmark on the new cell and put nothing on the old cell. If they’re the same, nothing changes. In either case, we deselect the cell to prevent it from being highlighted. Build and run, and you can see the checkmark appearing as you click on each cell.

Row Heights

You can change the height of one or more rows using a simple delegate method:

  1. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  2.     return 88;
  3. }

The default height is 44; this method would make the cells twice as high.

Indenting Rows

You can control the indent of each row with a delegate method:

  1. - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
  2.     return indexPath.row;
  3. }

This example would create a cascade of cells being indented further with each row. Going beyond a level of 5 or 6 looks really weird, so don’t go too far.

That’s the primary abilities that standard table views can offer. The data source and delegate protocols declare a few other features; we’ll touch upon some of them including sections and the index when we start working with files and persistence.

Download the project here.

Scroll to Top