iosarraysuicollectionviewuiedgeinsetssafearealayoutguide

programmatically adjust collectionView for safeArea


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


Solution

  • 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).