With iOS now available on more screen sizes, proficiency with Auto Layout has become a necessity. Unfortunately, I’ve observed many novice iOS developers whose first reaction to Auto Layout is to shy away. It can be intimidating, so in this post I’ll show a few common tricks that show the power and ease of use of Auto Layout.
Before trying to learn any fancy tricks, it’s important to understand the basics. In a previous post, I covered some of the underlying concepts. If your understanding of Auto Layout is shaky, that post will be a good starting point.
Animated Layout Update
Auto Layout works elegantly in combination with iOS’s existing animation APIs. It allows us to update the frames of several views at once, while animation blocks allow us to capture all changes to a view and animate them. Here’s an example of multiple views that perform an animated resize.
Here’s the code that’s driving the above animation:
This code is forcing Auto Layout to update from within an animation block. The block captures all the changes to the layout and animates them into place.
Text can be a pain, but Auto Layout makes it easy to deal with. In this example, we’re changing the size of a label to show how the UILabel class deals gracefully with being truncated.
This effect can be achieved with a very small amount of code:
In this example, the layout is squeezing the label. Conversely, one could create a layout where the length of the text determines the position of other views. For example, an image could be fixed to the right edge of the label. In this case, the image would move depending on the length of the text.
Truncating text also works with multi-line text labels. Our last example squeezed the label horizontally, but this one will squeeze it vertically:
The code for this example is exactly the same as the code from the last example. The only difference is which constraint is being updated.
More To Learn
This post shows some of the most basic uses of Auto Layout. In the next post, we’ll cover more advanced techniques.
As usual, all code used in this post is available on GitHub.