UICollectionView contentOffset changes with custom layout

Evan Cordell picture Evan Cordell · Jul 17, 2013 · Viewed 40k times · Source

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!

Answer

alexey.metelkin picture alexey.metelkin · Oct 8, 2013

I found the reason why this happens. Check the accepted answer from this question: Status bar and navigation bar appear over my view's bounds in iOS 7

Indeed, we could just set edgesForExtendedLayout or automaticallyAdjustsScrollViewInsets properties of UIViewController in IB (if you use Storyboard) of in viewDidLoad and it will fix our issue.

Just don't forget check for this property is available, because in iOS6 or prior it will cause crash:

if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
    self.automaticallyAdjustsScrollViewInsets = NO;
}

Regards!