How to get Height of Safe Area Programmatically Prior to IOS 11?

时间:2018-12-19 11:20:15

标签: ios swift layout uiview safearealayoutguide

Without using safeAreaLayoutGuide (I am targeting IOS 9+), is there any way to programmatically get the height of the "safe area" in IOS without having to create a new view (constrained to the safe area) solely for this purpose?

I can't set an outlet to the safe area because it's not a UIView... or even a class of any sort.

And if I simply use self.view.height in the ViewController, it's going to be too high (wrong).

Is there some other way to do it?

1 个答案:

答案 0 :(得分:8)

In a UIViewController you can use the top and bottom layout guides like this:

let safeAreHeight = self.view.frame.height - self.topLayoutGuide.length - self.bottomLayoutGuide.length

For UIView you can use the safeAreaLayoutGuide with a conditional check:

let verticalSafeAreaInset: CGFloat
if #available(iOS 11.0, *) {
  verticalSafeAreaInset = self.view.safeAreaInsets.bottom + self.view.safeAreaInsets.top
} else {
  verticalSafeAreaInset = 0.0
}
let safeAreaHeight = self.view.frame.height - verticalSafeAreaInset

As devices running iOS 9 and 10 have no safe area, it is safe to default to 0.0.