问题描述
几个月以来,我一直在使用 Swift 和 iOS。当涉及到 CollectionView 的倒数第二个项目时,我想下载一个新图像。我正在下载,但是 reloadData 函数不断重绘,collectionview 是最上面的。我怎样才能防止它上到顶部?
private func getRandomPhoto() {
let url = "https://source.unsplash.com/random/400x800"
do{
var a = try Data(contentsOf: URL(string: url)!)
images.append(UIImage(data: a)!)
} catch {
print("err")
}
dispatchQueue.main.async {
self.collectionView.reloadData()
}
}
这是我的控制器视图代码
extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath) as! ImageCollectionViewCell
cell.imageView.image = images[indexPath.row]
return cell
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
for cell in collectionView.visibleCells {
let indexPathh = collectionView.indexPath(for: cell)
if indexPathh?.row == images.count-1 {
let url = "https://source.unsplash.com/random/400x800"
getRandomPhoto()
}
}
}
}
我为这个问题制作了一个小视频。我希望很清楚。 https://github.com/Egemenclr/StajCase/blob/master/Örnek/problem.gif
解决方法
不要重新加载整个表格,而是为新下载的图像插入行
insertItems(at indexPaths: [IndexPath])
建议:不要一次又一次地下载相同的图像。最初下载并使用 NSCache 缓存它。当您再次需要图像时,尝试从缓存中获取。