Saoud Rizwan
Saoud Rizwan

Reputation: 659

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?

Upvotes: 15

Views: 9034

Answers (1)

nathangitter
nathangitter

Reputation: 9787

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.

Upvotes: 21

Related Questions