I’m beginning to implement AutoLayout, and I’m trying to piece together how I can hook up one of my custom UITableViewCell
classes properly. It usually has two UILabel
objects, one on top of another, much like the standard subtitle class. I’d like these two labels to be centred in the cell, regardless of the cell’s height, with a given padding between the two.
I assume I can do this by doing something like add the heights of the two labels, add the padding, then subtract that from the height of the cell, and divide by two. However, I’m curious semantically whether this is correct, since I’d be constraining them from the top and bottom of the cell, rather than from each other. Am I missing a trick here?
Secondly, there’s sometimes a third label stacked in there too, so three on top of one another. In that instance, I’d need two sets of the padding, etc., but the question becomes even more relevant: shouldn’t I be constraining them to each other, rather than to the top and bottom of the cell?
So, question is more of a semantic one: if I want to constrain multiple elements vertically inside a parent view, is there a smarter way to do this than the method I suggested above?
(I’m currently implementing AutoLayout entirely in code (using Masonry) since this cell in question has no XIB and isn’t in a Storyboard).
The correct approach is to use a container view, which derives its height from its subviews. The container view is then pinned to the centre of the cell - you wouldn't have any constraints linking the container to the top and bottom edges of the cell.
Within the container, the vertical constraints would be |[label1]-[label2]|
, which would make the container the height of the two labels plus the space, and the centre of the container view would be between the two labels.
If you added three labels, it would be |[label1]-[label2]-[label3]|
and the centre of the container would be in the centre of the middle label.
In each case the centre of the container would be at the centre of the cell, and you don't need to calculate anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With