0

I'm trying to set up a horizontally scrolling collection view that has cells with size CGSize(width: view.frame.width, height: view.frame.height). However, my cells are partially covered at the top by the navigation bar and using edge insets doesn't cleanly accommodate for all devices. How would I set the top of my cells to be at at the bottom of the new iPhone X navigation bar?

Here's the issue. The collectionView is set under the default navigationBar.

Here's the issue

Sunil
  • 3,404
  • 10
  • 23
  • 31
Explorer
  • 65
  • 1
  • 12

2 Answers2

3
if #available(iOS 11.0, *) {
    collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
} else {
    collectionView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}

You should probably also account for the bottom safe area as well, particularly for iPhone X (view.safeAreaLayoutGuide.bottomAnchor and bottomLayoutGuide.topAnchor).

Leon
  • 3,614
  • 1
  • 33
  • 46
trndjc
  • 11,654
  • 3
  • 38
  • 51
  • Yeah, I tried this about 10 minutes before you mentioned it. Don't know why I hadn't thought of this earlier. Always funny when the solution seems so clear! – Explorer Jan 29 '18 at 03:13
2

I think the marked answer is not the correct way to deal with safe areas on iOS.

With ScrollViews, TableViews and CollectionViews the standard way of dealing with them is to pin the edges to the ViewController's view but then set the content inset adjustment:

collectionView.contentInsetAdjustmentBehavior = .always

This means the content will scroll nicely within the bottom of the screen.

Leon
  • 3,614
  • 1
  • 33
  • 46