【问题标题】:CollectionView Cell images are changingCollectionView 单元格图像正在更改
【发布时间】:2017-11-21 03:02:48
【问题描述】:

cellForItemAt indexPath我打电话:

if cell.venueImageView.image == nil {
    cell.loadImage(imageURL: venue.imageURL)
}

loadImage 函数在UICollectionViewCell 类中:

func loadImage(imageURL: String) {
    print("LOAD IMAGE: \(imageURL)")
    Alamofire.request("http://***/" + imageURL).responseImage { response in
        if let image = response.result.value {
            self.venueImageView.image = image
        }
    }
}

它第一次显示正确的图像,但是当我向下然后向上滚动时,第一张图像出现在第二个单元格中,第二个图像出现在第一个单元格中,依此类推。我的代码有什么问题?

【问题讨论】:

    标签: swift uicollectionview


    【解决方案1】:

    在你的 UICollectionViewCell 中实现这个方法:

    override func prepareForReuse() {
        super.prepareForReuse()
    
        venueImageView.image = nil
    }
    

    每次重用单元格之前都会调用它。 此外,您应该尝试存储下载的图像。否则每次滚动时都必须加载图像。

    澄清一下:当您的单元格滚出屏幕以避免内存泄漏时,您的单元格会被重复使用。这意味着您下载的图像也会被删除。下次滚动到单元格时,图像消失了,必须再次下载。

    如果我是你,我会将所有下载的图像存储在 ViewController 中的一个数组中,并将图像设置为 cellForItemAt indexPathcell.venueImageView.image = imageArray[indexPath.row]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多