【问题标题】:Cell after scroll show image over image滚动后的单元格在图像上显示图像
【发布时间】:2014-12-25 14:28:34
【问题描述】:

我有 tableview,我想显示目录内一个文件夹中的所有图像,并且我有该目录的路径。我正在将图像加载到单元格中:

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    for (UIView * view in cell.contentView.subviews){
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }

    cell.imageView.image = nil;
    cell.accessoryType = UITableViewCellAccessoryNone;

    NSData *imgData = [NSData dataWithContentsOfFile:absoluteImagePath];
    UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:thumbNail];            
    [cell insertSubview:imageView atIndex:0];
}

但是当我向上和向下滚动时,我会在单元格内的图像上显示图像(旧图像在新图像下方可见,例如当我滚动到第一个位置时,我会在其他图像下方看到索引 0 的图像)。 有谁知道有什么问题,我是这个 iOS 编程的新手?

【问题讨论】:

    标签: ios objective-c ios7 ios8


    【解决方案1】:

    你应该

    • 子类化你的单元格,
    • 为图片创建一个出口,然后
    • 在情节提要中设计布局。

    好处:

    • 无需检查(cell==nil)
    • 您将需要编写更少的代码
    • 没有冗余视图创建错误的更简洁的解决方案

    【讨论】:

    • 或者,您可以只使用UITableViewCellimageView 属性。
    • @RinatKhanov 是的,但 OP 对图像视图的外观和位置的控制较少(可能不够)。
    【解决方案2】:

    当重复使用单元格时,[cell insertSubview:imageView atIndex:0]; 会向该单元格添加一个额外的UIImageView。建议创建一个自定义UITableViewCell 并在prepareForReuse 方法中删除UIImageView。识别要删除的UIImageView 的一种简单方法是向其添加tag。例如,

    imageView.tag = 1000;

    然后你可以找到图像视图

    UIImageView *imageView = [self.contentView viewWithTag:1000];
    if (imageView) {
        [imageView removeFromSuperview];
    }
    

    【讨论】:

      【解决方案3】:

      声明要在其中初始化单元格的 UIImageView。 例如

      if (cell==nil)
      { 
      UIImageView *image = [[UIImageView alloc]initWithFrame:yourFrame];
      [cell addSubView:image];
      }
      image.image = yourImage;
      

      或者,您可以在添加新的 UIImageView 作为子视图之前从单元格中删除所有子视图。

      【讨论】:

      • 如果单元格为零添加子视图?零对象?
      • 是的,只要尝试一下,它就会起作用。或者你可以像 mundi 说的那样子类化 UITableViewCell。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多