Get safe area inset top and bottom heights Get safe area inset top and bottom heights ios ios

Get safe area inset top and bottom heights


Try this :

In Objective C

if (@available(iOS 11.0, *)) {    UIWindow *window = UIApplication.sharedApplication.windows.firstObject;    CGFloat topPadding = window.safeAreaInsets.top;    CGFloat bottomPadding = window.safeAreaInsets.bottom;}

In Swift

if #available(iOS 11.0, *) {    let window = UIApplication.shared.keyWindow    let topPadding = window?.safeAreaInsets.top    let bottomPadding = window?.safeAreaInsets.bottom}

In Swift - iOS 13.0 and above

// Use the first element from windows array as KeyWindow deprecated

if #available(iOS 13.0, *) {    let window = UIApplication.shared.windows.first    let topPadding = window.safeAreaInsets.top    let bottomPadding = window.safeAreaInsets.bottom}


To get the height between the layout guides you just do

let guide = view.safeAreaLayoutGuidelet height = guide.layoutFrame.size.height

So full frame height = 812.0, safe area height = 734.0

Below is the example where the green view has frame of guide.layoutFrame

enter image description here


Swift 4, 5

To pin a view to a safe area anchor using constraints can be done anywhere in the view controller's lifecycle because they're queued by the API and handled after the view has been loaded into memory. However, getting safe-area values requires waiting toward the end of a view controller's lifecycle, like viewDidLayoutSubviews().

This plugs into any view controller:

override func viewDidLayoutSubviews() {    super.viewDidLayoutSubviews()    let topSafeArea: CGFloat    let bottomSafeArea: CGFloat    if #available(iOS 11.0, *) {        topSafeArea = view.safeAreaInsets.top        bottomSafeArea = view.safeAreaInsets.bottom    } else {        topSafeArea = topLayoutGuide.length        bottomSafeArea = bottomLayoutGuide.length    }    // safe area values are now available to use}

I prefer this method to getting it off of the window (when possible) because it’s how the API was designed and, more importantly, the values are updated during all view changes, like device orientation changes.

However, some custom presented view controllers cannot use the above method (I suspect because they are in transient container views). In such cases, you can get the values off of the root view controller, which will always be available anywhere in the current view controller's lifecycle.

anyLifecycleMethod()    guard let root = UIApplication.shared.keyWindow?.rootViewController else {        return    }    let topSafeArea: CGFloat    let bottomSafeArea: CGFloat    if #available(iOS 11.0, *) {        topSafeArea = root.view.safeAreaInsets.top        bottomSafeArea = root.view.safeAreaInsets.bottom    } else {        topSafeArea = root.topLayoutGuide.length        bottomSafeArea = root.bottomLayoutGuide.length    }    // safe area values are now available to use}