Auto Layout In iOS 8 – Layout Margins

Apple has added a few additions to both iOS 8 and OS X Yosemite that make working with Auto Layout even more of a no brainer than before. Over the next few weeks, I am going to take some time to write about each one of them to give fellow developers an idea of how to make use of these features in their products.

Up first is layout margins.

In iOS 8, Apple added the layoutMargins property on UIView. layoutMargins takes a UIEdgeInsets value that lets you explicitly define the whitespace that your views can use to guide where portions of the interface should be placed.

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.translatesAutoresizingMaskIntoConstraints = NO;
label.layoutMargins = UIEdgeInsetsMake(-20, -20, -20, -20);

For anyone that has used the topLayoutGuide or bottomLayoutGuide properties on UIViewController in iOS 7, laying out along a margin shouldn’t be a foreign concept. Those predefined values made it so that the content of your view wouldn’t be sunk underneath a transparent tab or navigation bar. With iOS 8, Apple has extended that functionality so that you can apply custom margins to any UIView that you work with.

To go with the new layout margins functionality, there are new attributes added exclusively for iOS 8 for establishing relationships with Auto Layout.

If these all look familiar, they should. They are pretty much equivalent to the old attributes you used such as NSLayoutAttributeLeft, NSLayoutAttributeRight, and NSLayoutAttributeCenterY. The only difference is that these new methods take into account the layoutMargin values that you set.

If you are targeting iOS 8, you should start adopting these new margin capabilities in your app, because it will lead to much cleaner code. Instead of having to use the constant value of your Auto Layout equation to insert padding, you can now just set the layoutMargins value specifically on the view, and let Auto Layout use those margins as part of its process.

If you’ve found this post useful, and want to learn more about how to best take advantage of Auto Layout in your OS X and iOS apps, be sure to purchase my new book Achieving Zen With Auto Layout