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.

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access