swift,  ios,  auto-layout

Unwanted padding in UICollectionView in iOS 10

On iOS 10, a collection view embedded in a view has unexpected padding at the top.

The issue:

On iOS 10, a collection view embedded in a view has unexpected padding at the top. Interestingly, works just fine on iOS 11.

Debugging shows that collection view contentSize is correct but contentOffset is wrong.

<UICollectionView: 0x7b7400061800; frame = (10 10; 300 242); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7b0c00026d60>; layer = <CALayer: 0x7b080003ca40>; contentOffset: {0, -64}; contentSize: {1200, 207}> collection view layout: <XoXo.cvLayout: 0x7b540005dc00>

contentOffset
▿ (0.0, -64.0)
  - x : 0.0
  - y : -64.0

contentInset
▿ UIEdgeInsets
  - top : 64.0
  - left : 0.0
  - bottom : 0.0
  - right : 0.0

The solution:

Set automaticallyAdjustsScrollViewInsets property of the view controller that contains the collection view to false.

self.automaticallyAdjustsScrollViewInsets = false

Note:

For iOS 11 the property was moved to the view (collection view) and was renamed to contentInsetAdjustmentBehavior.

        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }

Also setting bounce properties like bounces or alwaysBounceHorizontal does not solve the problem.

Explanation:

viewController.automaticallyAdjustsScrollViewInsets is true by default and it makes sense for scroll views that cover the entire screen. On iOS 10, the runtime will automatically adjust (by -64) collection view insets so that it is not covered behind the navigation bar or the status bar. Unfortunately that behavior completely ruins collection views that cover only certain parts of the screen.

Unwanted padding in UICollectionView in iOS 10

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox