CollectionView header content under status bar

六眼飞鱼酱① 提交于 2020-06-24 14:05:33

问题


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

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:

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

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.


回答1:


Found a solution:

collectionView.contentInset.top = -UIApplication.shared.statusBarFrame.height



回答2:


You should use safeAreaInsets for iphone X

if #available(iOS 11.0, *) {
    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
}



回答3:


Add 2 constraints:

1) view - superview

2) view - safeArea




回答4:


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

collectionView.contentInsetAdjustmentBehavior = .never



来源:https://stackoverflow.com/questions/48936137/collectionview-header-content-under-status-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!