O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required