Search code examples
iosuitableviewuilabelautolayoutcentering

Horizontally center two UILabels in a UITableViewCell


I have two UILabels in a UITableViewCell. Both have same width and height.

enter image description here

Consider these two labels as a group. I need to center this label group inside the cell horizontally. Important thing to note is that these cells are self-sizing. Meaning the cell's height depend on the content inside it so the height will vary. I need the label group to be centered no matter what the height is. The labels must keep that vertical space between them.

Currently I have set the following constraints to the two labels.

Top label - Leading Space to Superview, Top Space to Superview Bottom label - Leading Space to Superview, Bottom Space to Superview Both labels - Vertical Space

And the result is this.

enter image description here

The first cell, its displaying as I want to. But as you can see, when the height changes, the labels go crazy as expected since the Top Space and Bottom Space constraints are getting different values. I need those two labels to look like in the first cell in all cells.

Can anyone please tell me how to do this? Is it possible to do this in IB or do I have to dig into setting Auto Layout constraints in code?

Thank you.


Solution

  • Try to set for each label constraint Editor->Align->Vertical center in container