When I try to retrieve the safeAreaInsets in viewDidLoad in my view controller, it returns (0, 0, 0, 0) on the iPhone X, which I know is wrong. The documentation says that this will happen if the view is not part of the hierarchy or the view isn't visible. So my question is, where is the best place to retrieve the safeAreaInsets and then layout my subviews using these insets?
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 safe area of a view reflects the area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area reflects the area not covered by the screen's bezel.)
You need to use viewDidLayoutSubviews
instead of viewDidLoad
.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// your layout code here
}
Note: Unlike viewDidLoad
which is only called once, viewDidLayoutSubviews
is often called multiple times. Make sure to only set the frames inside viewDidLayoutSubviews
, and don't perform operations that should only happen once, like adding subviews.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With