在TableView中展示分层数据


问题


在一个TableView中显示分层数据。

方案


使用TableViewCell的缩进功能:

- (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;
}

为了给每个cell的内容视图一个边距,用缩进等级与缩进宽度简单的相乘。图4-5描述这些cell在TableView展示时的外观。

TableView-5

图4-5. 带缩进的TableView单元格

讨论


虽然可能很少发现很有用,但是你可以在iOS SDK的TableViewCell应用缩进。每个cell有2个想着属性。缩进等级和缩进宽度。缩进等级与缩进宽度简单相乘,所得的结果就是偏移量,根据这个值TableViewCell的内容会向左右两侧偏移。

例如,如果一个cell的缩进等级设置为2,缩进宽度设置为3,那么相乘的结果为6。这就意味着当呈现在TableView中时cell内容视图向右移动6个像素。

缩进级别定义为有符号的整数值,使你可以将给它的值为负。这显示将使单元格的内容视图向左偏移。

TableView的缩进级别允许程序员呈现分层数据,并由程序员来确定每个cell缩进级和缩进宽度。