UICollectionView delegate method cellForItemAtIndexPath:indexPath not called from sizeForItemAtIndexPath

左心房为你撑大大i 提交于 2019-12-13 13:21:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14377516/uicollectionview-delegate-method-cellforitematindexpathindexpath-not-called-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!