重用UITableViewCell的子类

时间:2012-03-21 14:58:33

标签: ios uitableview reusability

我正在尝试创建一个UITableViewCell的子类,它只包含一个UILabel属性“nameLabel”和一个UILabel属性“statusLabel”。为了正确出列单元格,我实现了 cellForRowAtIndexPath:方法像这样:

PS:statusLabel的文本来自twitter API,所以我必须将它的大小发送到 [[UILabel alloc] initWithFrame:]

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *CellIdentifier = @"StatusCellView";
    StatusCellView *cell = [tableView dequeueReusableCellWithIdentifier:
                        CellIdentifier];
    if (cell == nil) {
        cell = [[StatusCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    for (UIView *subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    if (![cell viewWithTag:kNameLabelTag]) {
        //init the nameLabel and [cell.contentView addsubview:nameLabel]
    }
    if (![cell viewWithTag:kStatusLabelTag]) {
        //init the statusLabel and [cell.contentView addsubview:statusLabel]
    }

    return cell;

正如您所看到的,当数据不是那么大时,这种方法很有效。但我的问题是:

  • 我认为反复删除和添加子视图会使性能变差。这是一种粗鲁的方式......
  • 我可以实现相同的功能而无需继承UITableViewCell。有没有办法利用子类?

1 个答案:

答案 0 :(得分:0)

我真的不明白为什么你要删除它们......这似乎是一种完全合理的方式:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"StatusCellView";
StatusCellView *cell = [tableView dequeueReusableCellWithIdentifier:
                    CellIdentifier];
if (cell == nil) {
    cell = [[StatusCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    //init the nameLabel and [cell.contentView addSubview:nameLabel];
    //init the statusLabel and [cell.contentView addsubview:statusLabel]
}
else {
    UILabel *nameLabel = [cell viewithTag:kStatusLabelTag];
    nameLabel.frame = newFrame;
    nameLabel.text = newText
    //etc, etc, etc
}
return cell;