为什么我的图像在 table 视图中一次又一次地加载?

Why are my images loaded again and again in a table view?

我正在创建一个应用程序来显示列表,每个列表都有一定数量的 x 图像显示在 table 单元格中。

要显示图像,我必须动态创建 UIImageView 并通过 for 循环将图像加载到单元格中(取决于从服务器调用接收到的数据)。

现在,我可以动态添加图像,但是当我滚动 table 视图时,cellForRowAtIndexPath 函数再次运行并且图像再次加载到单元格中,因此创建更多图片浏览量高于实际数据。

我想保持单元格中的图像计数不变,并且不想在 table 滚动时在单元格中创建更多图像。

函数代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Cellidentifier1 = @"ClassCell";

    ClassCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];

    // Configure the cell...
    long row = [indexPath row];

    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((250/10*count+10), 125, 20, 20)];
        [imageView setImage:[UIImage imageNamed:@"cricket_unselected.png"]];
        [cell addSubview:imageView];
    }

    return cell;
}

您的 ClassCell 可以为您解决这个问题。如果用于其他用途,再子类化即可;

@implementation ClassCell // or a new ClassCell subclass
- (id)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    // for loop..
  }
  return self;
}
@end

或者,您可以只使用 BOOL:

@interface ClassCell
@property BOOL hasImageViews;
@end

然后:

if (!cell.hasImageViews) {
  cell.hasImageViews = YES;
  // for loop..
}

旁注:不过,我不太确定为什么要将同一张图片多次添加到一个单元格中;您不是更有可能想要使用某种复选框吗?此外,您正在使用 t 进行迭代,但随后使用 count 应用框架,这意味着您的所有图像视图都相互重叠,因为它们在 cell 中具有相同的框架.