Kor_Dev
Kor_Dev

Reputation: 1

Collectionview loading data in wrong cells

ISSUE
I'm creating a pokedex screen that has a collection.
It loads the data of few pokemons according to their id.
Sometimes it works fine, but most of the times, the cells have duplicates of data - especially after scrolling.

If anyone could lend a helping hand, I will be much appreciated.
I've attached the collectionview dataSource code below.

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PokeCollectionViewCell.reuseId, for: indexPath) as! PokeCollectionViewCell
        
        print("indexPath NO DATA:", indexPath)
        cell.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        
        if let pokemon = encounteredId[indexPath.item] {
            cell.set(data: pokemon)
            print("indexPath PokeData:", indexPath)
        } else {
            cell.pokeImage.set(img: "clipboard.fill")
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        let animationDuration: Double = 1.0
        let delayBase: Double = 0.1
        
        let column = Double(cell.frame.maxX / cell.frame.width)
        let row = Double(cell.frame.minY / cell.frame.height)
        let distance = sqrt(pow(column, 3) + pow(row, 3))
        let delay = Double(indexPath.row) * delayBase
        
        UIView.animate(withDuration: animationDuration, delay: delay,
                       usingSpringWithDamping: 0.8, initialSpringVelocity: 4,
                       options: []
        ) {
            cell.backgroundColor = UIColor.black.withAlphaComponent(0.1)
            cell.transform = .identity
        }
    }

ScreenShot

My Guess
My take to the problem is that as the collectionview is dequeue reusing the cells, the data isn't being removed.
OR
that the indexPath is somehow jumbled up...
but I can't seem to understand how to approach the problem.

I was able to fix most of the problem through prepareForReuse(), but it also had issues as it loaded the backgroundColor of the cells .clear.

    override func prepareForReuse() {
        pokeImage.image = nil
        nameLabel.text = nil
        backgroundColor = .white.withAlphaComponent(0.7)
    }

Upvotes: 0

Views: 18

Answers (0)

Related Questions