Search code examples
iosobjective-ccocoa-touchios6uicollectionview

UICollectionView delegate method cellForItemAtIndexPath:indexPath not called from sizeForItemAtIndexPath


When I call

[collectionView cellForItemAtIndexPath:indexPath:]

from inside

[collectionView:layout:sizeForItemAtIndexPath:]

then the delegate method is not triggered. Any idea why not?

You can see it here.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CustomCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

    [cell configureWithData:self.data[indexPath.row]];

    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    CustomCell * cell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];

    return [cell preferredSize];
}

What I want to do is to ask the cell for its preferred size.

I could do

CustomCell * cell = (CustomCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];

but then a never-ending loop cycle is triggered

why is its delegate method not called as it should be?


Solution

  • I ended up with a Class method instead of an instance method:

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        return [CustomCell preferredSizeWithData:self.data[indexPath.row]; 
    
    }
    

    I made a Class method for the cell... to this method I provide the data that an actual instance at the specified indexPath would hold and calculate the preferred size

    I think that

    CustomCell * cell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
    

    triggers internally

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
    

    and what we see is some mechanism from Apple to prevent a loop cycle... because calling directly

    CustomCell * cell = (CustomCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];
    

    results in a loop cycle.