Shall i use UITraitCollection Class for Updating the Size Class constraints? Is this Best Practice to update the Constraints?
I have gone through the UITraitCollection, but don't know how to differentiate portrait and Landscape?
Shall i use UITraitCollection Class for Updating the Size Class constraints? Is this Best Practice to update the Constraints?
I have gone through the UITraitCollection, but don't know how to differentiate portrait and Landscape?
It sounds like you want a different layout based on iPad orientation. If adjusting constraint values is all you need to do, you can check the
UITraitCollection
'shorizontalSizeClass
andverticalSizeClass
properties. The size class properties values can be found at the Apple documentation forUIUserInterfaceSizeClass
. I can't vouch for this being best practice, but I don't see anything wrong with it. An alternative to checking theUITraitCollection
would be to checkUIInterfaceOrientationIsPortrait
as seen below in the code snippet.A more complex scenario requires the use of completely different constraints for landscape vs portrait. You could handle adding those constraints programmatically, or you can use a different size class to add the constraints and then create an
IBOutletCollection
for the constraints for each size class that are based on the orientation.For example, I used wAnyhRegular to setup my portrait iPad layout and then used wRegularhAny to setup my landscape iPad layout. (Although you may want to use wRegular/hRegular as one of your orientation layouts since iPad registers as wRegular/hRegular when you check the
UITraitCollection
. Hopefully the code below demonstrates how I went about it:My portrait constraints can be seen below. My landscape has 3 constraints as well.
I then apply the constraints as noted below (not shown, viewDidLoad executes
_needsiPadConstraintsApplied = YES;
):And finally, you may find this exploration of size classes helpful.