Search code examples
iosuicollectionviewswift5reloaddata

How can I prevent redrawing when new data arrives using collectionview.reloaddata in swift5?


I've been working with Swift and iOS for several months now. I want to download a new image when it comes to CollectionView's penultimate item. I'm downloading, but the reloadData function is constantly redrawing and collectionview is top. How can I prevent it from going to the top?

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()
    }
}

and here is my controller view codes

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()
                
            }
        }
    }
}

I made a small video for the problem. I hope it's clear. https://github.com/Egemenclr/StajCase/blob/master/Örnek/problem.gif


Solution

  • Don't reload the whole table, instead insert rows for newly downloaded images

    insertItems(at indexPaths: [IndexPath])
    

    suggestion: Don't download the same image only again and again. Download initially and cache it with NSCache. Try to fetch from cache when you need the image again.