如何创建具有多个单元格类型的分组表视图?

时间:2013-04-02 14:01:00

标签: ios objective-c uitableview

我没有使用故事板,它是iOS 6.

当所有单元格类型相同但我需要具有多种类型单元格的分组表格视图时,我会做什么。举个例子,假设第一个单元格需要UITableViewCellStyleValue1,第二个单元格需要UITableViewCellStyleSubtitle,第三个单元格是自定义单元格(UITableViewCell子类有一个xib因此可以与registerNib:forCellReuseIdentifier:一起使用。

大多数情况下,我不确定构建tableView:cellForRowAtIndexPath:的最佳方法。但我不确定是否应该注册自定义单元格或所有单元格。

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:3)

你走在正确的道路上。由于您的自定义单元格正在其他地方使用,因此xib是从中加载它的好地方。就实现而言,你可以做这样的事情。

假设您的桌面视图为“静态”且有三个单元格,您可以在viewDidLoad中注册自定义笔尖:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UINib *customCellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
    [self.tableView registerNib:customCellNib forCellReuseIdentifier:@"CustomIdentifier"]
}

然后在cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = nil;

    if(indexPath.row == 0) {

        cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier1"];

        if(cell == nil) {

            cell = [[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleValue1
                                           reuseIdentifier:@"CellIdentifier1"];
        }
    }
    /* Cell 2 ommited for brevity */
    else if(indexPath.row == 2) {

        //Just to demonstrate the tableview is returning the correct type of cell from the XIB
        CustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"CustomIdentifier"];
        cell = customCell;
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

最后在IB中为Xib设置正确的Identifier为单元格。

Xib - Cell in IB

<强>更新

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.row == 0) {
        cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
    }
    else {

        //custom cell here
        //cell.textfield.text = @"blah blah";
    }
}

配置单元格方法在某种程度上适用于主要使用NSFetchedResultsController(及其使用的delegate)的tableview单元格。

这是使用适当内容重置重复使用的单元格的简便方法,并使cellForRowAtIndexPath:更易于阅读。我甚至制作了多个版本的configureCell,如configureCustomCell1:atIndexPath,以进一步提高可读性。

希望这有帮助!

答案 1 :(得分:0)

如果您使用静态表,则不需要重用标识符或其他任何内容,因为不会重复使用单元格。只需将表格设置为“Grouped”样式的“静态单元格”,然后设置所需的部分数量。您可以单击“表视图部分”并设置该部分中的行数(并设置您可能需要的任何页眉/页脚)。

Storyboard Example

然后根据需要配置单元格。您可以选择默认单元格,也可以将单元格设置为“自定义”,然后从对象库中拖动UI组件。您可以为静态表格单元格中的组件设置IBOutletsIBActions,就像在普通视图中对组件一样。

Configure Cell