UICollectionView delegate method cellForItemAtIndexPath: indexPath is not called from sizeForItemAtIndexPath

When i call

[collectionView cellForItemAtIndexPath:indexPath:] 

from the inside

 [collectionView:layout:sizeForItemAtIndexPath:] 

then the delegate method does not start. Any ideas 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 ask the cell about its preferred size.

i could do

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

but then an endless loop cycle starts

why isn't his delegate method invoked the way it should be?

+4
source share
1 answer

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 the Class method for the cell ... for this method, I provide the data that the actual instance will contain at the specified indexPath , and indexPath preferred size

I think that

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

launches internally

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

and what we see is some kind of mechanism from Apple to prevent a loop cycle ... because the call is direct

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

leads to a loop cycle.

+7
source

All Articles