Reputation: 24205
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?
Upvotes: 0
Views: 80
Reputation: 17241
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 that you update the layouts for all your size classes.
Say you have a simple "register view" with a username text field where users can claim their unique username. You want to give the user immediate visual feedback if the username he typed in is already taken or not.
You decide that on a compact size class (iPhone in portrait mode) there is just enough space to show a litte red cross (❌) on the right edge of the text field. On the iPhone 6/7 Plus in landscape mode however, there is enough space to show the user a little more information and so you choose to show a label "Username taken, please try another one!" next to the red cross on the regular size class.
Now every time the user has entered a new character in the text field you can validate the input and then update the UI like this:
func updateUI(isUsernameAvailable: Bool) {
redCross.hidden = isUsernameAvailable
usernameTakenLabel.hidden = isUsernameAvailable
}
At this point you can be sure that the UI is up-to-date no matter how often the user rotates the devices. If the usernameTakenLabel
was not instantiated here you would have to somehow remember that the label should be hidden/visible once it shows up with an extra instance variable and then use that variable to actually hide/reveal the label once it is instantiated i.e. when the size class width changes which bloats your view controller and is pretty error prone.
Upvotes: 1