Some cells are blank when I get data from API and showing it in collection view

174 Views Asked by At

I have a collection view and I'm fetching data from themoviedb api. I get the cast for each movie. And each cell contains profile image view, name label and character label. The problem is that some cells are blank when I get the data. Though I've configured all views in the cell, the problem was not resolved.

Very similar to the problem on this link CollectionView duplicate cell when loading more data

Image of the problem image of the problem

here is cellForItemAt function

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch type {
        case .cast:
            if let castCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreditsCollectionViewCell", for: indexPath) as? CreditsCollectionViewCell {
                castCell.configureCastCell(with: self.cast[indexPath.row])
                return castCell
            }
            return UICollectionViewCell()
        case .crew:
            if let crewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreditsCollectionViewCell", for: indexPath) as? CreditsCollectionViewCell {
                crewCell.configureCrewCell(with: self.crew[indexPath.row])
                return crewCell
            }
            return UICollectionViewCell()
        default:
            return UICollectionViewCell()
        }
    }

CreditsViewController class

import UIKit
import SDWebImage

class CreditsCollectionViewCell: UICollectionViewCell {

    //MARK: - Outlets
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var characterLabel: UILabel!
    @IBOutlet weak var spinner: UIActivityIndicatorView!



    override func prepareForReuse() {
        super.prepareForReuse()
        nameLabel.text = nil
        characterLabel.text = nil
        imageView.image = nil
    }




    //MARK: - Configure cell for the cast
    public func configureCastCell(with cast: MovieCast) {
        if let spinner = spinner {
            spinner.startAnimating()
        }
    
        guard let profilePath = cast.profilePath else {
            return
        }
        let path = "https://image.tmdb.org/t/p/original" + profilePath
        if let profileUrl = URL(string: path) {
            DispatchQueue.main.async {
                self.imageView.sd_setImage(with: profileUrl, completed: nil)
                if let spinner = self.spinner {
                    spinner.removeFromSuperview()
                }
            }
        }
    
        self.nameLabel.text = cast.name
        self.characterLabel.text = cast.character
    }
}
0

There are 0 best solutions below