iosswiftuicollectionviewuicollectionviewcelluicollectionviewdelegateflowlayout

UICollectionView cell ignores UICollectionViewDelegateFlowLayout - sizeForItemAt


I am trying to layout the size of my collectionViewCell so that in each row there are 7 cells (easy right?).

The cell is very simple, it only has a UILabel with top, left, bottom and right constraints of 0.

I have setup the sizeForItemAt method as below, made sure my controller is a collectionViewDelegateFlowLayout, collectionViewDelegate and collectionViewDataSource, and that collectionview.delegate and .datasource = self.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let safeScreenWidth = self.view.frame.size.width - 30

        let width: CGFloat = (safeScreenWidth / 7)
        let height: CGFloat = 40.0

        return CGSize(width: width, height: height)
    }

The method is called correctly (checked with break points and print()) however the cell decides to totally ignore the size given and comes out with a size just enough to contain its label's text (if the label's text is empty the app crashes for "Invalid parameter not satisfying: !CGSizeEqualToSize(size, CGSizeZero)").

I tried setting different sizes such width = 200, height = 200; but nothing changes the cell is always very small, as I said, just enough to fit its label's text.

A quick solve is setting height and width constraints for the label in cellForItemAt, but I want to understand why sizeForItemAt does not work.


Solution

  • For some reason, automatic estimated size has bigger priority, than calculated in sizeForItemAt method.

    Try to set collectionViews Estimate Size to None

    CollectionView - Size Inspector - Estimate Size