Search code examples
iosiphone-xsafearealayoutguide

iOS safeAreaLayoutGuide gives full 812 height for iPhone X


This is also described but not answered in Why does this iPhone X UIView not get safeAreaLayoutGuide?

I create a totally-new from-scratch single-view Universal iOS app and add only these three lines of code to viewDidLoad(). I launch the iPhone X Simulator in portrait mode. Here's what I get:

let safeSize = view.safeAreaLayoutGuide.layoutFrame.size
// Returns (375.0, 812.0) — why full size?

let window = UIApplication.shared.delegate!.window!!
let safeSize2 = window.safeAreaLayoutGuide.layoutFrame.size
// Returns (375.0, 734.0) — this is what I expected.

Why does the root view controller's root view not return the expected safe area?


Solution

  • SafeAreaInsets:

    You obtain the safe area for a view by applying the insets in this property to the view's bounds rectangle. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the edge insets in this property are 0.

    The same is true for the SafeAreaLayoutGuide:

    When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views.

    Therefore since the view has not laid out yet in viewDidLoad or visible, it is 0.. When you do it in viewDidLayoutSubviews, you will see it is non-zero and valid insets are set.