Alternate Layouts in iOS - Size Classes
In my latest iOS project I have discovered the power of size classes.
Adaptivity is the key to why this feature exists. A single layout file can be used for multiple device sizes without any code changes to adapt to different screen sizes.
make it even easier to adapt your user interface to any size or orientation.
Previously I would add and remove constraints in the code behind depending on checks for screen width and height. How annoying! But now I can handle those constraint changes within the layout file in Xcode. How convenient!
How it works
Essentially there are two main breakpoints per side which are regular and compact. So there is a compact width and a compact height, and a regular width and a regular height.
So for example, you can apply constraints that only apply if the screen is a compact width (3.5 inch, 4-inch, and 4.7 inch iPhones in portrait or landscape).
There are 9 different combinations of these width and heights.
In reality, you can essentially target 4 different device sizes with one layout file and therefore have alternate layouts and constraint values for each of the following:
- any iPad (Landscape and Portrait)
- iPhone 6 Plus (Landscape)
- any iPhone (Portrait)
- any iPhone except 6 Plus (Landscape)
Simply turn on the size classes option in Xcode’s Interface Builder and have fun (obviously there’s more to it than that — more details here https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Size-ClassSpecificLayout.html#//apple_ref/doc/uid/TP40010853-CH26-SW1).
Example use , 2 and 1 column layout
One example use is creating a two column layout for the iPad and iPhone 6 Plus (landscape) size groups. Then for the other two size classes you add and remove the necessary top, bottom, leading and trailing constraints (and any others) to create a one column layout.
This saves having two xib files and loading the correct one per device, and also saves having to remove and add constraints using custom code on rotation of the iPhone 6 Plus. Essentially it saves bothering your developer.
How will you use size classes?