滚动时集合视图可重复使用的单元格问题



我正在使用集合视图在列表中显示 gif。 现在面临单元格可重用的问题,同时向上或向下滚动集合视图的单元格。

就像itemA在列表中排在第一位,itemB在列表中排在第二位。但是当我在集合视图中滚动数据时。物品的位置放错了地方。就像某个时间项目A排在第5位或有时在列表中的任何地方。 我知道我认为这是可重复使用的单元格的用途,但不知道如何挽救它。 请帮忙。

集合视图单元格项目在

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GifCell", for: indexPath as IndexPath) as? GifCell else {
fatalError()
}
if gifArr.count > 0 {
let urlString = self.gifArr[indexPath.row]
let url = URL(string: urlString)!
DispatchQueue.global().async {
let imageData = try? Data(contentsOf: url)
let imageData3 = FLAnimatedImage(animatedGIFData: imageData) // this is the 3rd pary library to show the gifs on UIimageview's
DispatchQueue.main.async {
cell.imageView.animatedImage = imageData3
cell.textLabel.text = String(indexPath.row)
}
}
}
return cell
}

GifCell中,您可以实现prepareForReuse()方法:

执行准备视图以供再次使用所需的任何清理。

override func prepareForReuse() {
super.prepareForReuse()
imageView.animatedImage = nil
textLabel.text = ""
}

: 此时,每次调用cellForItemAt方法时,都会重新加载 URL,因此稍后,您可能希望找到一种方法来缓存图像,而不是继续重新加载它们。

第一个解决方案:您可以缓存数据,每次检查是否有数据时,请使用缓存。 您可以使用此链接,但UIImage替换为礼物类型!

或 试试这个,我没有测试它

if let giftAny = UserDefaults.standard.value(forKey: "giftUrl") {
//cast giftAny to Data
// use cached gift
} else {
// cache gift
let giftData = try? Data(contentsOf: url)
UserDefaults.standard.setValue(giftData, forKeyPath: "giftUrl")
//use gift
}

第二种解决方案:不要重复使用单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell(style: .default, reuseIdentifier:"Cell")
return cell
}

但在这种情况下,如果你有很多单元格,内存泄漏是不可避免的。

最新更新