自定义UITableViewCell没有正确出列

时间:2012-06-09 01:29:10

标签: objective-c uitableview reuseidentifier

我有一个带有3个自定义UITableViewCells的UITableView,我现在正在这样出发:

    if (indexPath.row == 0) {
         static NSString *CellIdentifier = @"MyCell1";
         MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
         if (cell == nil) {
             cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
         }
         return cell;
    }
    if (indexPath.row == 1) {
         static NSString *CellIdentifier = @"MyCell2";
         MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
         if (cell == nil) {
             cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
         }
         return cell;
    }
    if (indexPath.row == 2) {
         static NSString *CellIdentifier = @"MyCell3";
         MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
         if (cell == nil) {
             cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
         }
         return cell;
    }

我尝试过多种方式,但问题是即使我仍然使用不同的标识符将它们全部排除,当我滚动tableView时,有时我的第一个单元格出现在我的第三个单元格的位置反之亦然。似乎有一些奇怪的缓存正在进行中。

有谁知道为什么?感谢。

1 个答案:

答案 0 :(得分:1)

由于您总是分配相同的单元类,因此您发布的代码没有任何意义。单元标识符不用于标识特定单元格,而是用于标识您正在使用的子类。

所以将代码更改为:

static NSString *CellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
     cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;

并根据indexPath.section和indexPath.row在willDisplayCell中正确设置单元格内容:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
相关问题