Search code examples
iosswiftuicollectionviewnslayoutconstraint

How can I avoid gaps below a UICollectionView search bar on devices with notches?


I have a UICollectionView with contents that I want to scroll below the transparent navigation bar. I also have a UIView that contains a UISearchBar that the user can toggle by tapping a button on the navigation bar:

UICollectionView with contents that scroll below the transparent nav bar and custom search bar

As the image above shows, this works well for a device without a notch. I achieve this by setting the content inset top to searchController.searchBar.frame.size.height and the content offset top to -collectionView.contentInset.top - (navigationController?.navigationBar.frame.size.height ?? 0) - UIApplication.shared.statusBarFrame.size.height).

For a device with a notch, there is a gap between the search bar and the contents when the search bar is first displayed. Then, when I start searching, the spacing is correct. If I cancel and the contents don't fit on the screen (that is, the collection view is scrollable), there's a gap the size of the search bar. If the contents do fit on the screen, there is no such gap.

UICollectionView with contents that scroll below the transparent nav bar and custom search bar on device with notch

The constraints are set in the storyboard. The only way I could find to get the behavior I wanted was to constrain the collection view top to the top layout guide bottom - 64 which is certainly not ideal.

Clearly, something is wrong with my mental models here. How do I get the desired behavior on devices with and without notches and ideally avoid the magic number in the constraint?


Solution

  • This behaviour is due to safe area layout guides. For device with notch, top constraint calculates distance from Safe Area(starting from notch).

    To solve this, go to storyboard -> select CollectionView -> select top constraint. You will see few options related to constraint on Size inspector. Change Second Item to SuperView instead of Safe Area.

    screenshot of size inspector