Ios 滚动时集合视图可重用单元格问题
我正在使用集合视图显示列表上的gif。 现在,在集合视图上下滚动单元格时,面临单元格可重用问题 与类似,项目a在列表中位于第一位,而项目b在列表中位于第二位。 但是当我在collection视图中滚动数据时。物品放错地方了。比如一些时间项目排在第五位,或者有时排在列表的任何地方。 我知道我认为这是可重复使用电池的用途,但不知道如何补救。 Plss帮助 集合视图cellForItemAtIos 滚动时集合视图可重用单元格问题,ios,iphone,swift3,uicollectionview,swift4,Ios,Iphone,Swift3,Uicollectionview,Swift4,我正在使用集合视图显示列表上的gif。 现在,在集合视图上下滚动单元格时,面临单元格可重用问题 与类似,项目a在列表中位于第一位,而项目b在列表中位于第二位。 但是当我在collection视图中滚动数据时。物品放错地方了。比如一些时间项目排在第五位,或者有时排在列表的任何地方。 我知道我认为这是可重复使用电池的用途,但不知道如何补救。 Plss帮助 集合视图cellForItemAt func collectionView(_ collectionView: UICollectionView,
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
中,您可以实现prepareforeuse()
方法:
执行任何必要的清理,以准备再次使用视图
注意:
此时,每次调用
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
}
但在这种情况下,如果您有许多单元,内存泄漏是不可避免的。这是否回答了您的问题?请告诉我如何缓存GIF的数据。
FLAnimatedImage(animatedGIFData:imageData)
的类型是什么?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell(style: .default, reuseIdentifier:"Cell")
return cell
}