Exploring AutoLayout on the example of UITableViewCells
Are you one of those persons, who did understand the Spring & Struts layout model perfectly. One of those, who was more likely to use some additional container views to reach a specific layout than starting to learn AutoLayout? I am one of them. And still, for simple layouts, I think the Spring & Struts model is both faster and easier.
But if it comes to more complex layouts, the AutoLayout system can save you a lot of code. So in this article I want give a basic introduction to AutoLayout with InterfaceBuilder by showing, how to create the four well known standard UITableViewStyles of a UITableViewCell using AutoLayout:
(Left original, right custom layouting)
Before discussing the specific constraints, here are three general hints, when using IB for AutoLayout.
I do not show the basic UITableViewCellStyleDefault in my examples. You can figure it out yourself. But let's have a look at the other three layouts starting with UITableViewCellStyleSubtitle.
This is a quite static layout. Two labels, one on the top, one on the bottom. But we want the length to be always as long as the text is, not any longer. Also the maximum length should be no longer than the cell itself minus 10px margin. How can we achieve this? Here is an overview of all constraints for both labels:
As you can see there are no violet constraints left. I will shortly explain them all. On the textLabel we have:
And on the detailTextLabel:
We have a label with a fixed width on the left and a flexible width label on the right. As in the last layout, the right label should not grow any larger than the cell itself (minus 10px margin). These are the constraints:
On the textLabel, we have:
On the detailTextLabel, we have:
This is the most flexible one. Because both labels are next to each other, but they can both have any size they want (within the cell bounds). So if the first label needs most of the space, the second one shrinks and vice versa. These are the constraints:
On the textLabel, we have:
On the detailTextLabel, we have:
In the end, if you did understand the system once and know the buttons in InterfaceBuilder it is straight forward and you can create layouts, that would have needed code before AutoLayout. It's a very strong system. And if you do it with IB it is easier to debug and create, than by code. I recommend to always use IB. But there are layouts, where you need to use code. E.g. if you want to have relative constraints like "1/2 of the height", or aspect ratio stuff like "height=width", or to do animations, etc.