4.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 4-5 depicts how these cells look when displayed inside a table view.

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 to the right or left.

For instance, if the indentation level of a cell is set to 2 and its indentation width is set to 3, the resultant value is 6. This means the content view of the cell is shifted to the right by six pixels when displayed in a table view.

Note

The indentation level is defined as a signed integer value, making it possible for you to assign negative values to it. This will obviously shift the content view of your cells to the left.

The indentation level assigned to table view cells enables programmers to present hierarchical data, and it is up to the programmer to determine the indentation level and the indentation width of each cell.

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