Search code examples
iosautolayout

How to vertically center a group of labels relative to an image?


This is what I want to achieve:

I want the image to be vertically centered in the cell and the two labels (which are placed inside another view) to be vertically centered relative to the image (as a group - this is why they are in a view).

Below is my attempt:

The second label has a lower content hugging value. As you can see, when there is a small text, because of the content hugging, the text in the second label wouldn't be placed directly under the first one, thus having a lot of empty space. Also, the first label should be placed lower.

When there is enough text, it looks good.

How should I treat the case when the text is small?

Thanks.


Solution

  • I used the other suggestions to use a stack view plus the accepted answer here to make the alignment of the labels work: How to center both vertical and horizontal inside a UIStackView .I don't touch the content hugging priority.

    First I set up a horizontal stack view that will serve as a container. I pin it to the Top, Bottom, Leading and Trailing ends of the cell. Its size will be the size of the cell. Its alignment is center. It means it will center its components vertically. The distribution is Fill - the components will take the whole space horizontally.

    Content Stack View plus other constraints

    I put an image view and a vertical stack view as its components. I set up the image view with fixed height and width. I guessed this is what is wanted. I put the two labels as components of this second stack view. The vertical stack view has alignment Fill. It will fill all space horizontally. The distribution is also Fill. It will fill all space vertically, but this space is intrinsic and set by the labels as far as I understand it. So it will grow and shrink with their content.

    Vertical Stack View plus other constraints

    And that’s it if I have understood the requirements correctly.

    One more thing. Since I see that the text in the last picture you posted is cut at some point - if this is what you want, set one height constraint at the second label, that is less or equal than some number you choose, so the label cannot grow beyond it.