Search code examples
swiftuicollectionviewuiimageviewuicollectionviewcellcalayer

UICollectionViewCell imageView doesn't load without scrolling


I have some cells in my collectionView, oriented vertically.
Every cell has got an image in it's left part and that image loads correctly.
But after I added a rounded top-right corner to the image doesn't automatically load when the screen in on.
Here is the method that is being called in cellForItemAt

func setAvatarImage(imageName: String) {
        self.addSubview(avatarImageView)
        layoutIfNeeded()
        avatarImageView.layer.roundCorners(corners: [.topRight], radius: UIDevice.current.userInterfaceIdiom == .pad ? 85 : 40)
        avatarImageView.contentMode = .scaleAspectFit
        avatarImageView.image = UIImage(named: imageName)
        avatarImageView.snp.makeConstraints { (make) in
            make.height.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
            make.left.equalToSuperview()
        }
    }

Here is also the roundCorners method, CALayer extension, which worked perfectly on every element in my app. Also here it works perfectly but the images are not loading without scrolling up and down in the collectionView:

func roundCorners(corners: UIRectCorner, radius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = .clear) {
        let maskPath = UIBezierPath(
            roundedRect: bounds,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        
        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        
        mask = shape

        let borderLayer = CAShapeLayer()
        borderLayer.path = maskPath.cgPath
        borderLayer.lineWidth = borderWidth
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.frame = self.bounds
        addSublayer(borderLayer)
    }

Solution

  • Solved by adding:

    layoutIfNeeded()