3

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?

Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100
  • Are you looking for `topLayoutGuide` and `bottomLayoutGuide`? If so you can check its `length` properties and subtract it from the view's height. See https://developer.apple.com/documentation/uikit/uiviewcontroller/1621367-toplayoutguide. – André Slotta Dec 19 '18 at 11:30
  • https://stackoverflow.com/a/49683870/9086770 – trndjc Dec 19 '18 at 11:42
  • While there may be some overlap in answers, this is a different question... that one is asking specifically about ios 11 or higher, this one is asking specifically about lower than 11. – Nerdy Bunz Dec 19 '18 at 23:30

1 Answers1

14

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.

Sparga
  • 1,517
  • 12
  • 21