Codey
Codey

Reputation: 1233

UICollectionViewCell is wider than specified in sizeForItemAt

I've created a UICollectionView using UICollectionViewFlowLayout. I specify the size of my UICollectionViewCell inside the collectionView(_ collectionView:layout:sizeForItemAt:) function:

extension FlickrPhotosViewController: UICollectionViewDelegateFlowLayout {
    let itemsPerRow: CGFloat = 3
    
    func collectionView(
        _ collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAt indexPath: IndexPath
    ) -> CGSize {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow
        
        return CGSize(width: widthPerItem, height: widthPerItem)
    }
}

I am expecting to see three images in one row (left image), however the images all have different size (right image)

Correct layout Wrong layout

Upvotes: 0

Views: 274

Answers (1)

Codey
Codey

Reputation: 1233

UICollectionViewFlowLayout has a property estimatedItemSize which is likely set to UICollectionViewFlowLayout.automaticSize. This leads to the layout overriding the specified size in the sizeForItemAt function.

To fix this either set the property of the UICollectionView layout to layout.estimatedItemSize = .zero (for example in viewDidLoad) or use Interface Builder, select the Collection View Flow Layout object and in the Size Inspector set Estimate Size from Automatic to None

Set estimated size of collection view flow layout

Upvotes: 1

Related Questions