有条件地使用自定义UITableViewCell类还是常规UITableViewCell?

时间:2014-08-22 18:54:18

标签: ios objective-c uitableview

我已经将UITableViewCell子类化,以便我可以自定义其部分布局。我没有为它创建一个XIB。我一直在使用自定义类,只需在Interface Builder中定义每个静态单元格的类。因为他们是静态单元格,所以我不需要实现cellForRowAtIndexPath

但是现在我只想在某个条件成立时才使用该自定义单元格类,否则我希望该单元格的类成为默认的UITableViewCell类。

我已恢复静态单元格的类以删除Interface Builder中的自定义类。所以现在我需要一些方法来改变代码中每个单元格的类。我相信这需要在cellForRowAtIndexPath中完成,但我不知道如何动态创建自定义单元格类并使用该单元格,否则使用默认值。

2 个答案:

答案 0 :(得分:2)

您可以为不同类型的单元格使用两种不同的重用标识符。像这样设置你的条件:

UITableViewCell *cell;
if (needCustomCell) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"CustomIdentifier"];
    if (!cell) {
        cell = [[MyCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CustomIdentifier"];
    }
    ... // Do configuration specific to your custom cell
} else {
    cell = [tableView dequeueReusableCellWithIdentifier:@"PlainIdentifier"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlainIdentifier"];
    }
    ... // Do configuration specific to your regular cell
}
... // Do configuration common to both kinds of cell
return cell;

答案 1 :(得分:0)

在cellForRowAtIndexPath方法中,为每个案例创建所需的表格视图实例

UITableViewCell *cell = nil;
if (conditionIsTrue) {
    cell = [[MyCustomTableViewCell alloc] init];
}
else {
    // create default table view cell
}

或类似的......