Recently I was solving a problem similar to this. The difference is that in my view the top unsafe areas has to be filled while the bottom ones doesn't. Another difference is that my background view is actually in a scrollView
, which make the constraints setting more complex.
I tried the "statusBar"
solution mentioned above, however I guess the view hierarchy had be changed since iOS 13, thus this would result to crash.
Finally I came out with this solution that solves the problem:
Firstly add Status Bar Bg View at the very top of the view controller view, align its top, leading, and trailing to safe area's top, leading, and trailing (statusBarBgView
in the code).
At the same time, set the original fill background (bgView
)'s top constrains to Status Bar Bg View's bottom.
Then in viewDidLoad()
, call the following method:
private func fillSafeAreaIfNeeded() {
if let _ = UIApplication.shared.keyWindow?.safeAreaInsets.top {
statusBarBgView.translatesAutoresizingMaskIntoConstraints = false
statusBarBgView.topAnchor.constraint(equalTo: view!.topAnchor).isActive = true // This line fills up status bar
bgView.topAnchor.constraint(equalTo: statusBarBgView!.bottomAnchor).isActive = true
}
else {
statusBarBgView.frame = CGRect.zero
}
}
Note that by constraining bgView
's topAnchor with statusBarBgView
's bottomAnchor, the gap between both view could be avoided while scrolling.