CollectionView header content under status bar
Asked Answered
M

5

6

Here's a collection view constrained to top, left, right, and bottom of the superview with safe area layout guide enabled:

enter image description here

I want my collection view header to be shown under the status bar. I've achieved this for iPhone 4 - 8+ screen dimensions by unchecking Safe Area Layout Guide in the size inspector for the controller's main view, and adding the following code:

collectionView.contentInset = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0)

This looks great for non iPhone X view sizes:

enter image description here

However, for the iPhone X, this leads to the following output:

enter image description here

The iPhone X has its own dimensions for the status bar. Adjusting the top inset further does work, but will over-offset the other device sizes. I am wondering if there's an more elegant way to achieve this behaviour.

Menes answered 22/2, 2018 at 19:56 Comment(0)
M
10

Found a solution:

collectionView.contentInset.top = -UIApplication.shared.statusBarFrame.height
Menes answered 22/2, 2018 at 20:6 Comment(0)
T
8

The previous solutions work, but this might be the easiest one:

collectionView.contentInsetAdjustmentBehavior = .never

Tip answered 26/11, 2019 at 16:38 Comment(1)
Indeed, but this will cause the bottom to go under the bottom safe area. This is not something that you might want.Poleyn
V
3

This will do

collectionView.contentInsetAdjustmentBehavior = .never
Voltmer answered 25/12, 2020 at 16:1 Comment(1)
this must be marked as accepted answer, you are my hero!Albumose
W
2

You should use safeAreaInsets for iphone X

if #available(iOS 11.0, *) {
    if let top = UIApplication.shared.keyWindow?.safeAreaInsets.top {
        collectionView.contentInset = UIEdgeInsets(top: -top, left: 0, bottom: 0, right: 0)
    }
} else {
    // Fallback on earlier versions
    collectionView.contentInset.top = -UIApplication.shared.statusBarFrame.height
}
Westerman answered 28/2, 2018 at 14:11 Comment(0)
M
1

Add 2 constraints:

1) view - superview

enter image description here

2) view - safeArea

enter image description here

Margarethe answered 28/2, 2018 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.