Ios – safeAreaInsets in UIView is 0 on an iPhone X

iosiphoneiphone-xswift

I am updating my app to adapt it for iPhone X. All views work fine by now except one. I have a view controller that presents a custom UIView that covers the whole screen. Before I was using UIScreen.main.bounds to find out the size of the view before all layout was done (I need it for putting the correct itemSize for a collectionView). I thought that now I could do something like
UIScreen.main.bounds.size.height - safeAreaInsets.bottom to get the right usable size. The problem is, safeAreaInsets returns (0,0,0,0) trying on an iPhone X (Simulator). Any ideas? In other views, I get the right numbers for safeAreaInsets.

Thank you!

Best Answer

I recently had a similar problem where the safe area insets are returning (0, 0, 0, 0) as soon as viewDidLoad is triggered. It seems that they are set fractionally later than the rest of the view loading.

I got round it by overriding viewSafeAreaInsetsDidChange and doing my layout in that instead:

override func viewSafeAreaInsetsDidChange() {
 // ... your layout code here
}