7

在实现自定义UICollectionViewLayout子类时发现了这种奇怪的行为。我设置了除collectionViewContentSize. 所有的细胞都出现在我预期的地方,但是contentView太长了。看起来大约是应该的两倍。

我实现了下面的方法来获得正确的contentSize. 虽然,它现在是预期值,prepareLayout每次视图滚动一个像素时都会调用它。这意味着如果我从 0,0 滑动到 0,500,prepareLayout就会被调用 500 次!

我有什么collectionViewContentSize可能导致这种情况?

- (CGSize)collectionViewContentSize {
    UICollectionViewLayoutAttributes *leftAttributes = (UICollectionViewLayoutAttributes *)self.layoutInfo[@"segmentCell"][[NSIndexPath indexPathForItem:[self.collectionView numberOfItemsInSection:0]-1 inSection:0]];
    UICollectionViewLayoutAttributes *rightAttributes = (UICollectionViewLayoutAttributes *)self.layoutInfo[@"segmentCell"][[NSIndexPath indexPathForItem:[self.collectionView numberOfItemsInSection:1]-1 inSection:1]];
    float leftHeight = leftAttributes.frame.size.height + leftAttributes.frame.origin.y;
    float rightHeight = rightAttributes.frame.size.height + rightAttributes.frame.origin.y;
    float maxHeight = leftHeight > rightHeight ? leftHeight : rightHeight;
    return CGSizeMake(self.collectionView.bounds.size.width, maxHeight);
}
4

2 回答 2

13

尽管根据文档 [0]shoulInvalidateLayoutForBoundsChange:应该默认返回 NO,但事实并非如此。一旦我实现它并让它在所有情况下都返回 NO,prepareLayout就不再在每次边界更改时调用它。这似乎是 UICollectionViewLayout 中的一个错误。

[0] http://developer.apple.com/library/ios/#documentation/uikit/reference/UICollectionViewLayout_class/Reference/Reference.html

于 2013-04-09T14:55:19.577 回答
0

您希望发生这种情况的一个原因是,在使用自定义布局时,您可能希望单元格的大小根据内容偏移量而变化,例如当您在 iPhone X 上向上滑动时,Y 值决定了细胞。这使您不必为您可能想要的特定效果处理单独的手势识别器。

于 2018-07-30T09:46:31.047 回答