Mathieu Robert
Mathieu Robert

Reputation: 334

Collection cell wrongly resized in reloadData

I don't know why but the cells of my collectionView are automatically wrongly resized after a reloadData.

After first init, then after reloadData :

First init after Reload

I'm using UICollectionViewDelegateFlowLayout to define the size of the cell but it don't take care of it :

  func collectionView(_ collectionView: UICollectionView,
                      layout collectionViewLayout: UICollectionViewLayout,
                      sizeForItemAt indexPath: IndexPath) -> CGSize {
    let paddingSpace = sectionInsets.left * (2 + 1)
    let availableWidth = view.frame.width - paddingSpace
    let widthPerItem = availableWidth / 2

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

  func collectionView(_ collectionView: UICollectionView,
                      layout collectionViewLayout: UICollectionViewLayout,
                      insetForSectionAt section: Int) -> UIEdgeInsets {
    return sectionInsets
  }

  func collectionView(_ collectionView: UICollectionView,
                      layout collectionViewLayout: UICollectionViewLayout,
                      minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return sectionInsets.left
  }

When execution come in the cellForItemAt, the cell have the right size, the shadow is created in this function and it have the right width.

One last thing is that only the width is resized, the height stay as I want.

Does any one have an idea why the width is resized wrongly after the reloadData ?

Upvotes: 0

Views: 1332

Answers (2)

Pavel L.
Pavel L.

Reputation: 41

In my case, the reason for such behaviour was a missing call to the super.prepareForReuse in overridden method in my custom UICollectionViewCell cell.

So I simply added it and the problem was solved. :]

override func prepareForReuse() {
    super.prepareForReuse() // <-- that was the clue!

    // your code here
}

Upvotes: 2

Andy
Andy

Reputation: 462

I was having a similar issue when making an extension of the UICollectionViewDelegateFlowLayout and it turns out that setting the collectionView's Estimated Size to "None" in the storyboard (Size Inspector) solved it.

As stated in the Xcode 11 Release Notes:

Cells in a UICollectionView can now self size with Auto Layout constrained views in the canvas. To opt into the behavior for existing collection views, enable “Automatic” for the collection view’s estimated size, and “Automatic” for cell’s size from the Size inspector. If deploying before iOS 13, you can activate self sizing collection view cells by calling performBatchUpdates(_:completion:) during viewDidLoad(). (45617083)

So, newly created collectionViews have the attribute "Estimated Size" set as "Automatic" and the cell's size is computed considering its subview dimensions, thus ignoring the UICollectionViewDelegateFlowLayout extension methods, even though they are called.

Upvotes: 4

Related Questions