UICollectionView委托方法cellForItemAtIndexPath:未从sizeForItemAtIndexPath调用indexPath

时间:2013-01-17 10:56:24

标签: ios objective-c cocoa-touch ios6 uicollectionview

当我打电话

[collectionView cellForItemAtIndexPath:indexPath:]

来自内部

[collectionView:layout:sizeForItemAtIndexPath:]

然后不会触发委托方法。知道为什么不呢?

你可以看到它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];
}

我想要的是询问单元格的首选大小。

我能做到

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

然后触发一个永无止境的循环周期

为什么它的委托方法不应该被调用呢?

1 个答案:

答案 0 :(得分:7)

我最终使用了Class方法而不是实例方法:

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

    return [CustomCell preferredSizeWithData:self.data[indexPath.row]; 

}

我为单元格创建了一个Class方法...对于这个方法,我提供了指定indexPath的实际实例将保存并计算首选大小的数据

我认为

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

内部触发

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

我们看到的是Apple的一些机制,可以防止循环循环...因为直接调用

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

导致循环周期。