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

Nerdy Bunz picture Nerdy Bunz · Dec 19, 2018 · Viewed 7.4k times · Source

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?

Answer

Sparga picture Sparga · Dec 19, 2018

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.