Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

safeAreaInsets return wrong values in viewDidLoad, where's the best place to get it?

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?

like image 930
Saoud Rizwan Avatar asked Sep 19 '17 01:09

Saoud Rizwan


People also ask

How do I get 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.

What Safeareainsets Swift?

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.)


1 Answers

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.

like image 117
nathangitter Avatar answered Sep 28 '22 10:09

nathangitter