【问题标题】:Programmatically add UIImageViews to UITableViewCell以编程方式将 UIImageViews 添加到 UITableViewCell
【发布时间】:2025-12-19 01:15:11
【问题描述】:

对于我的 tableView 中的每个单元格,我想以编程方式添加 UIImageViews,因为每个单元格将有不同数量的 imageViews。当我插入一个新单元格时,它包含来自下一个单元格的 imageViews。如何确保 imageViews 不会与其他单元格重叠?

这是我在自定义UITableViewCell 中使用的方法来添加图像视图。

 -(void)setImageViews:(int)images{
      x=0;
      for (int i=0;i<images;i++){
           UIImageView *imgV=[[UIImageView alloc]initWithFrame:CGRectMake(x,5, 36, 36)];
           [imgV setImage:[dic objectForKey:@"image"]];
           [self addSubview:imgV];

           x=x+36;
      }
 }

我认为我必须为每个单元格保留一个唯一标识符并检查它是否与当前单元格匹配。像这样的

-(void)setImageViews:(int)images forIndexPath:(int)row{
     if ((!self.cellIdentifier)||([self.cellIdentifier isEqualToString:[NSString stringWithFormat:@"%i", row]])){
         self.cellIdentifier=[NSString stringWithFormat:@"%i", row];
          x=0;
          for (int i=0;i<images;i++){
               UIImageView *imgV=[[UIImageView alloc]initWithFrame:CGRectMake(x,5, 36, 36)];
               [imgV setImage:[dic objectForKey:@"image"]];
               [self addSubview:imgV];

               x=x+36;
          }
     }
}

但这不起作用

【问题讨论】:

  • 你对一个单元格可以包含的图像数量有一个已知的最大限制吗?
  • @AdamPro13 我没有在上面添加这个,但是如果 imageView 在屏幕边缘被切断,我会打破循环。因此,在被切断之前,最大图像非常适合。
  • 您应该将图像子视图添加到 self.contentView 而不是 UITableViewCell 直接

标签: ios objective-c uitableview


【解决方案1】:

在自定义 UITableViewCell 中实现

override func prepareForReuse() {
    contentView.subviews.forEach { (subView) in
        if let imageView = subView as? UIImageView {
            imageView.removeFromSuperview()
        }
    }
}

【讨论】:

    最近更新 更多