1

I am using

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: 400, height: 600)
}

to specify my CollectionView's cell sizes. It works fine but as soon as I add a width constraint (UILabel.width == ContentView.width) to my UILabel inside the ContentView of the cell, the cell's width shrinks to the intrinsic width of the UILabel.

I am using UICollectionViewDelegateFlowLayout and horizontal scrolling.

How can I force the ContentView to stick to the cell size I specified and let the subviews follow the auto layout constraints?

Jakub
  • 13,712
  • 17
  • 82
  • 139
Kashif
  • 4,642
  • 7
  • 44
  • 97
  • If you cell width is 400 then minus padding of both side of uilabel and set it direct instead of only adding left right constraint – Pravin Tate Oct 18 '19 at 15:04
  • My cell size is actually going to be calculated based upon screen size so can't do it your way. – Kashif Oct 18 '19 at 15:40
  • But you write return CGSize(width: 400, height: 600) it means your all cell size should be this. – Pravin Tate Oct 18 '19 at 15:43
  • Yes, cell should be 400x600 but it is not when I add size constraints on UILabel. – Kashif Oct 18 '19 at 15:45
  • There is two for if cell size is dynamic first you need to get intrinsicContentSize of that label and second one is write your flowLayout and return respective size from this method – Pravin Tate Oct 18 '19 at 15:50
  • Can you please show some graphics for both cases? – Kamran Oct 24 '19 at 09:43

1 Answers1

10

The problem is that in the storyboard your collection view's Estimate Size is configured to Automatic:

enter image description here

You need to set it to None if you want your sizeForItemAt implementation to be obeyed rather than the internal constraints.

matt
  • 515,959
  • 87
  • 875
  • 1,141