3.7. Displaying Hierarchical Data in Table Views

Problem

You want to be able to display hierarchical data in a table view.

Solution

Use the indentation functionality of table view cells:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* result = nil;
  
  static NSString *MyCellIdentifier = @"SimpleCells";
  
  result = [tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
  
  if (result == nil){
    result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:MyCellIdentifier];
  }
  
  result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",
                           (long)indexPath.section,
                           (long)indexPath.row];
  
  result.indentationLevel = indexPath.row;
  result.indentationWidth = 10.0f;
  
  return result;
  
}

The indentation level is simply multiplied by the indentation width in order to give a margin to the content view of each cell. Figure 3-5 depicts how these cells look when displayed inside a table view.

Table view cells with indentation

Figure 3-5. Table view cells with indentation

Discussion

Although you might rarely find it useful, you can apply indentation to table view cells in the iOS SDK. Each cell can have two properties related to indentation: indentation level and indentation width. The indentation level is simply multiplied by the indentation width, and the resultant value is the offset by which the table view cell’s content is shifted ...

Get iOS 5 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.