SafeArea does not work in viewDidLoad

David Wu
2 min readOct 9, 2018

--

When I start working on pure code layout, not using Storyboard, problem with SafeArea starts to emerge.😥 You will get wrong safeAreaInsets in viewDidLoad.

Solution

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.

Even though it will still work in viewDidLayoutSubViews , the more accurate place to acquire SafeArea’s layout is at viewSafeAreaInsetsDidChange() .

You can see the difference of SafeArea’s layout between viewDidLoad, viewSafeAreaInsetsDidChange() and in transition in the screenshots above. 😀

Besides directly setting the frame of UIView equal to SafeArea’s frame, more commonly, we’d use constraints to deal with layouts from designer.

--

--