hasan83 hasan83 - 18 days ago 6
iOS Question

Xcode traits views not nil

As known different views can be added for each screen unit class(Regular, Compact) By picking the desired unit classing then clicking the Vary for Traits button.

Then, connect the views to your controller twice using outlets. one for general and one for that unit class.


In viewDidLoad I printed the values of both views and noticed that both
of them are not nil.


Shouldn't I have one of the views equal to nil since this is not its unit class? How does view traits realy work?

Answer

All views (and constraints) are instantiated and referenced with their corresponding outlets when your storyboard scene (or nib) is loaded - no matter what size class they are installed on.

From Apple's Auto Layout Guide:

When the system loads a scene, it instantiates all the views, controls, and constraints, and assigns these items to the appropriate outlet in the view controller (if any). You can access any of these items through their outlets, regardless of the scene’s current size class. However, the system adds these items to the view hierarchy only if they are installed for the current size class.

This is because your view's size class does not only vary depending on the device, it may also change when you rotate your device or do multitasking on an iPad. When you change your layout as a response to a user action (like a tap) you really wanna make sure to update the layouts for all your size classes.