How to reload only one cell in a collectionView?

Viewed 13896

I have a collectionView and I have two problems. First, the scrolling is too laggy. My collectionView receives the data from an API in url and look like this:

enter image description here

This is my code:

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if imageUrl.count >= 4 {
            activity.stopAnimating()
            activity.isHidden = true
        }else{
            DispatchQueue.main.async {
                self.myCollectionView.reloadData()
            }
        }

        return imageUrl.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "myViewCell", for: indexPath) as! myViewCell

        if let url = NSURL(string: imageUrl[indexPath.row]){
            if let data = NSData(contentsOf: url as URL){
                cell.carImageView.contentMode = UIViewContentMode.scaleAspectFit
                cell.carImageView.image = UIImage(data: data as Data)
            }
        }

        cell.firstLabel.text = firstLabelArray[indexPath.row]

        if secondLabelArray != []{
            cell.secondLabel.text = secondLabelArray[indexPath.row]
        }

        return cell
    }
}

The second problem that I have is I need refresh only the third cell in my collection view. That is my secondLabel but when I try with myCollectionView.reloadData() that reloads all of my cells. I need to refresh the third cell every second.

3 Answers

The problem with the lag in the collectionView can be the way tha you use NSData, consider use Alamofire Image, like this

if imageUrl.count > 0 {
        let eachImage = imageUrl[indexPath.row]
        Alamofire.request(eachImage).responseImage(completionHandler: {(response) in
            print("answer\(response)")
            if let image = response.result.value{
                DispatchQueue.main.async {
                    cell.ImageView.image = image
                }
            }
        })
        }

Collection View laggy because you trying to show images from url on main thread. Show some default images in cells before you download images from api and then update cells on main thread

Related