SafeAreas for both orientation before adding a view to the hierarchy

Hi everyone,

For various optimization purposes, I want to get the device's max display size without the safe areas for both portrait and lanscape.

I can use the UIWindow's safeAreaInsets, but that only gives me the current safe areas, not the one for opposite layout (assuming there is only portrait and landscape).

I had a look at UITraitCollections (I really thought I could achieve it with it), but it seems like a dead end.

Anyone can help me with that ?

Thanks!

Answered by Frameworks Engineer in 732757022

There is no way to query the safeAreaInsets for a non-current state, and there is no guarantee that they would be consistent (they usually are, but system state can always change in such ways that the safeAreaInsets you saw at the launch of your app are no longer valid later during the execution of your app).

Why not do it in viewWillLayoutSubviews() ?

Then you'll get the right values and can do all the preparation you need there.

Thanks for your answer Claude31. For various reasons being :

  • I need to send to the server the display area before even beginning to load a view
  • That will not give me the insets for all orientation

Besides, I can use the UIApplication.shared.windows.first?.safeAreaInsets to get the same result I guess ;-)

FYI, I tried with appearance, but safeAreaInsets are .zero and safeAreaLayoutGuide is still nil, that's a shame :-/

     let appearance = UICollectionView.appearance(for: self.traitCollection,                            whenContainedInInstancesOf: [UIViewController.self, UINavigationController.self])     print(" \(appearance.safeAreaInsets) - \(appearance.safeAreaLayoutGuide)")

Accepted Answer

There is no way to query the safeAreaInsets for a non-current state, and there is no guarantee that they would be consistent (they usually are, but system state can always change in such ways that the safeAreaInsets you saw at the launch of your app are no longer valid later during the execution of your app).

@radada we don't know what type of optimization you intend to do on server. But having the server to take into account device orientation is surprising for me. That's a presentation task that should (IMHO) be better done on device. What if some day iphone comes with square screen ? But of course, you alone know the constraints of your app.

Thanks to all of you for these answers and support, I appreciate ;-)

SafeAreas for both orientation before adding a view to the hierarchy
 
 
Q