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

标签 ios objective-c uitableview

这是我的代码:

- (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;
}

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

Correct Display

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

enter image description here enter image description here

您可以看到第一行有一个 UIImage ,下面几行有文本,而我显然没有在我的代码中设置它。

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

谢谢。

最佳答案

你真的应该重新使用表格 View 单元格,因为如果你一直重新创建它们会带来很多开销,即注释掉的代码是正确的。
接下来,docs说:“tableView:cellForRowAtIndexPath: 中的 TableView 委托(delegate)在重用单元格时应始终重置所有内容。”
如果您不重置内容,它将再次显示。
所以我建议你设置

cell.imageView.image = nil; 

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

关于ios - UITableViewCell 在滚动时显示错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23774179/

相关文章:

iphone - UIImageView 中的 UIImage 大小

ios - UITableView 页脚与 iOS 11 中的单元格重叠

iphone - 如何创建包含多行代码的宏?

objective-c - 在 Swift 中声明全局宏

objective-c - 双重赋值在 Objective-C 中有效吗?

iphone - iOS NSMutableArray 卡住

ios - 找不到成员 'Fade'

ios - 创建文档时出现错误 : "xcrun: error: unable to find utility "docsetutil", 不是开发人员工具或位于 PATH 中

iphone - sqlite 随机文件已加密或不是数据库

ios - 如何为 UILabel 添加换行符?