Search code examples
iosios11iphone-x

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?


Solution

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