Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewLayout prepareLayout is called for any scrolling

Found this strange behavior while implementing a custom UICollectionViewLayout subclass. I set up the subclass methods except for collectionViewContentSize. All the cells showed up where I expected, but the contentView was too long. Looked to be about double what it should be.

I implemented the method below to get the correct contentSize. Though, it's now the expected value, prepareLayout is called every single time the view scrolls one pixel. That means if I swipe from 0,0 to 0,500, prepareLayout is called 500 times!

What is it about my collectionViewContentSize that could cause that?

- (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);
}
like image 817
brodney Avatar asked Apr 09 '13 04:04

brodney


1 Answers

Although according to the docs [0] shoulInvalidateLayoutForBoundsChange: is supposed to return NO by default, it wasn't. Once I implemented it and had it return NO in all cases, prepareLayout is no longer called with every bounds change. That seems like a bug in UICollectionViewLayout.

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

like image 128
brodney Avatar answered Oct 20 '22 01:10

brodney