子类化UITableViewCell(可能使用id)

时间:2012-02-28 03:41:55

标签: ios uitableview

当我在表格视图中设置自定义单元格时,我正试图找到一种不重复代码的方法。我目前有一个BaseCell类,从UITableViewController继承,然后是BaseCell的两个子类:CellTypeOne和CellTypeTwo。这是我目前正在使用的那种设置:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *type = [self.rowTypes objectAtIndex:indexPath.row];

    if ([type isEqualToString:@"Type 1"]) {
        CellTypeOne *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 1"];

        cell.picture.image = // An image
        cell.caption.text = // A caption

        cell.author.text = // An author

        return cell;
    }

    else if {[type isEqualToString:@"Type 2"]) {
        CellTypeTwo *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 2"];

        cell.picture.image = // An image
        cell.caption.text = // A caption

        cell.number.text = // A number

        return cell;
    }
}

由于某些细胞类型的设置属性相同,我想知道是否有办法做这样的事情:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *type = [self.rowTypes objectAtIndex:indexPath.row];

    id cell;

    if ([type isEqualToString:@"Type 1"]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 1"];

        // Cast cell to (CellTypeOne *)?

        cell.author.text = // An author
    }

    else if {[type isEqualToString:@"Type 2"]) {
        CellTypeTwo *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 2"];

        // Cast cell to (CellTypeTwo *)?

        cell.number.text = // A number
    }

    cell.picture.image = // An image
    cell.caption.text = // A caption

    return cell;
}

这样我就可以为每个子类做特定于类的设置,然后对两者进行通用设置。我实现这一点的唯一方法是每次我需要使用它时使用单元格,这样的事情:

[(BaseCell *)cell picture].image = // An image

必须在每一行上投射单元格似乎比开始使用几行重复代码更有效,但我只是想弄清楚最好的方法来解决这个问题。

1 个答案:

答案 0 :(得分:2)

您可以制作cell类型的BaseCell*变量,以避免在ifs之外进行转换:

BaseCell *cell;

if ([type isEqualToString:@"Type 1"]) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 1"];
    [[cell author] setText:/*an author*/];
} else if {[type isEqualToString:@"Type 2"]) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell 2"];
    [[cell number] setText: /* a number */];
}

cell.picture.image = // An image
cell.caption.text = // A caption

或者,您可以保留id的类型,并使用方法调用语法而不是成员(点)语法之外 ifs:

id cell;
// ... the code from your post
[[cell picture] setImage: /* an image */];
[[cell caption] setText: /* a caption */];

最后,您可以通过在ifs中声明其他变量来完全避免强制转换方括号:

BaseCell *cell;

if ([type isEqualToString:@"Type 1"]) {
    CallTypeOne *cellOne = [tableView dequeueReusableCellWithIdentifier:@"Cell 1"];
    cellOne.author.text = // An author
    cell = cellOne;
} else if {[type isEqualToString:@"Type 2"]) {
    CellTypeTwo *cellTwo = [tableView dequeueReusableCellWithIdentifier:@"Cell 2"];
    cellTwo.number.text = // A number
    cell = cellTwo;
}
相关问题