iosuicollectionviewuicollectionviewlayoutcontentoffset

UICollectionView contentOffset changes with custom layout


I have a UICollectionView with a custom UICollectionViewLayout (actually, I'm using this nice layout).

I set contentOffset = CGPointZero in viewDidLoad. After viewDidLoad, however, the offset is -20, and the content gets pushed down like so:


picture

(It should be flush with the line). I'm loading the collection view layout in interface builder. It seems that my problem is very similar to this one, however the solutions there don't work for me.

I tried modifying collectionViewContentSize in my layout implementation to ensure it was always greater than the size of the collectionView. Although this means I can scroll my content down (it's shorter than the height of the collectionView) and hide the extra space, I can also scroll back up to see it.

Nothing seems to work!


Solution

  • The only solution I could come up with that had barely-acceptable behavior:

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        if (self.collectionView.contentOffset.y < 0) {
            self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, 0.0);
        }
    }
    

    As well as setting the height of the content to fmax(self.collectionView.frame.size.height + 20, [self stackedSectionHeight]) in collectionViewContentSize

    This removes the space above the section header, but it removes the "bounce" from the top. A pretty sub-optimal solution, but fairly acceptable.

    I'll accept a better answer if anyone has one, or if I find one I'll update this answer.