Search code examples
iosswift3uiimageviewuicollectionviewuicollectionviewcell

Swift3 - Cells with image is not displayed


Im trying to set the background view as an image but it never displays the cells with images. I can scroll down so I know that there are indeed cells there but there are no background images, whenever i scroll really fast you can kind of make out the correct image but it vanishes quickly.

Any ideas why?

heres my code:

let image: UIImageView = {
    let imgview = UIImageView()
    imgview.image = UIImage(named: "myImage")
    imgview.contentMode = .scaleAspectFit
    imgview.clipsToBounds = true
    return imgview
}()

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-id", for: indexPath)
    cell.contentView.addSubview(image)
    cell.backgroundView = image
    return cell
}

Solution

  • You should not call addSubview method in cellForItemAt. Because cellForItemAt is called many many times.

    Try this code:

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-id", for: indexPath)
    
        UIGraphicsBeginImageContext(cell.frame.size)
        UIImage(named: "myImage")?.draw(in: cell.bounds)
        if let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            cell.backgroundColor = UIColor(patternImage: image)
        }
        return cell
    }