Dmitry Chaschin
Dmitry Chaschin

Reputation: 11

Wrong cell data if fast scroll CollectionView swift 5

Can anybody help me with CollectionView? I parce JSON from some API, and get String values - title and image adress, then assign that Data to custom collectionViewCell in method cellForItem(). BUT than i fast scroll the collection view some cell can be with wrong images, or duplicate images. I also override method prepareForReuse in my custom cell class and set cell.image = UIImage() , but it didnt work. Please help me to understand what wrong) Sorry for my poor English...

collectionViewController

'''

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Result",
                                                      for: indexPath) as! ResultCell
        let film = results[indexPath.item]
        cell.name.text = film.title
        cell.imageView.layer.borderColor = UIColor(white: 0, alpha: 0.3).cgColor
        cell.imageView.layer.borderWidth = 2
        cell.imageView.layer.cornerRadius = 10
        cell.layer.cornerRadius = 10
        // setUp image for cell
        cell.imageView.image = nil
        contentManager.getImage(film.poster.image, cell.imageView)
        return cell
    }

'''

method get image '''

func getImage(_ url_str:String, _ imageView:UIImageView) {
        let url:URL = URL(string: url_str)!
        let session = URLSession.shared
        let task = session.dataTask(with: url, completionHandler: {(data, response, error) in
            if data != nil {
                let image = UIImage(data: data!)
                if(image != nil) {
                    DispatchQueue.main.async(execute: {
                        imageView.image = image
                        imageView.alpha = 0
                        UIView.animate(withDuration: 1, animations: {
                            imageView.alpha = 1.0
                        })
                    })
                }
            }
        })
        task.resume()
    }

'''

Cell custom class '''

class ResultCell: UICollectionViewCell {
    @IBOutlet  var imageView: UIImageView!
    @IBOutlet var name : UILabel!
    
    
    override func prepareForReuse() {
       
        self.imageView.image = UIImage()
        self.name.text = nil
         super.prepareForReuse()
    }
}

'''

Upvotes: 1

Views: 185

Answers (0)

Related Questions