UICollectionView: the UICollectionViewCell object is always null in sizeForItemAtIndexPath

I have a collection view that contains various custom cells.

These cells contain various contents that vary in size.

Cells are defined in the storyboard, so registration is not required in the code.

All I want to do is resize in the delegate method depending on the content:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { id cellAtIndexPath = [collectionView cellForItemAtIndexPath:indexPath]; NSLog(@"The cell: %@", cellAtIndexPath); ... eg calling sizeToFit methods and cumulating the sizes of the cells' subviews ... } 

The method is called as expected for each cell, but cellAtIndexPath always returns NULL, regardless of what I tried. Therefore, I cannot access the cell object in the indexPath view or its contents.

Any suggestions why I cannot access the cell object?

+7
source share
1 answer

The collectionView:layout:sizeForItemAtIndexPath is called by the layout object of the collection view stream. The layout asks for the size of the cell at a time before the cells are added to the collection view. You will need to calculate the required cell size "at your discretion" and return it.

+11
source

All Articles