4

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.

  • 1
    did you check this method is getting called. If you set cell size to be automatic in storyboard, this method will not be getting called. – Swati Nov 14 '19 at 14:15

1 Answers1

26

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

Viktor
  • 1,020
  • 1
  • 9
  • 22
  • 7
    After half year my own answer helped me in new project Checked on XCode 11.4.1 and Swift 5 – Viktor May 12 '20 at 06:45
  • This did not help me! The cell height is not updated but the contentSize of the scollview is made higher with the som of height values of the cells! – MQoder Apr 21 '21 at 07:33