Search code examples
swiftuicollectionviewautolayoutuicollectionviewflowlayout

UICollectionViewCell not forcing Cell Size


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?


Solution

  • 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.