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

谁说胖子不能爱 提交于 2021-02-19 05:19:07

问题


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:


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.



来源:https://stackoverflow.com/questions/53850172/how-to-get-height-of-safe-area-programmatically-prior-to-ios-11

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