ios - UITableViewCell在滚动时显示错误的数据

Pha*_*oan 2 objective-c uitableview ios

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifierNormal = @"CellNormal";
static NSString *CellIdentifierTracking = @"CellTracking";

switch (self.mapState) {
    case MapStateNormal:
    {
//            UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifierNormal];
//            if (cell == nil) {
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierNormal];
//            }
        [cell.textLabel setText:@"abc"];
        return cell;
    }
    case MapStateTracking:
    {
//            UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifierTracking];
//            if (cell == nil) {
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierTracking];
//            }
        if (indexPath.row == 0) {
            [cell.textLabel setText:@"Lorem ipsum"];
        } else {
            NSURL *url = [LoremIpsum URLForPlaceholderImageFromService:LoremIpsumPlaceholderImageServicePlaceKittenCom
                                                             withWidth:1024
                                                                height:1024];
            [cell.imageView setImageWithURL:url
                           placeholderImage:[UIImage imageNamed:@"MenuButton"]];
           }
        return cell;
    }
    default:
        break;
}
return nil;
}
Run Code Online (Sandbox Code Playgroud)

这段代码工作得很好但不是最佳实践,因为我UITableViewCell每次都重新创建.它显示如下:

正确显示

但是,当我取消注释上面的那些行以启用时dequeueReusableCell,表格显示其单元格有这样的错误(黄色部分是我的代码):

在此输入图像描述 在此输入图像描述

你可以看到UIImage第一行和下面某些行中有文本,而我显然没有在我的代码中设置它.

我该怎么做才能解决这个问题?或者我应该坚持使用第一种方法?

谢谢.

Rei*_*ner 6

您应该重新使用表视图单元格,因为如果您一直重新创建它们会产生大量开销,即外部注释的代码是正确的.
接下来,文档说:"表格视图的委托tableView:cellForRowAtIndexPath:应始终在重用单元格时重置所有内容."
如果您不重置内容,它将再次显示.
所以我建议你设置

cell.imageView.image = nil; 
Run Code Online (Sandbox Code Playgroud)

在你的-(UITableViewCell *)tableView:cellForRowAtIndexPath:(NSIndexPath *)indexPath方法.