swiftuicollectionviewuicollectionviewcelluicollectionviewdelegateflowlayout

UICollectionViewDelegateFlowLayout is not changing cell bounds


I have problem with setting shadow path for UICollectionViewCell which has a relative width to collectionView bounds.

Im using storyboard constraints, setting up shadow in AwakeFromNib method and resizing cell with sizeForItemAt method

 //cell awakeFromNib    
    override func awakeFromNib() {

    self.backgroundColor = UIColor.white

    self.contentView.layer.cornerRadius = 2.0
    self.contentView.layer.borderWidth = 1.0
    self.contentView.layer.borderColor = UIColor.clear.cgColor
    self.contentView.layer.masksToBounds = true

    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOffset = CGSize(width: 0, height: 2.0)
    self.layer.shadowRadius = 2.0
    self.layer.shadowOpacity = 0.5
    self.layer.masksToBounds = false
    self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}



// collection view method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let height: CGFloat = 288

    return CGSize(width: collectionView.bounds.size.width-20, height: height)
}

Cell bounds:

AwakeFromNib method - (307.0, 288.0)

Expected - (300.0, 288.0)

What is the problem?


Solution

  • The problem is that the bounds/frame are changing if your cell is layouted.

    Add this to your collectionViewCell - subclass:

        override func layoutSubviews() {
        super.layoutSubviews()
            self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds,  cornerRadius: self.contentView.layer.cornerRadius).cgPath
        }