Search code examples
iosstoryboardxibuistackview

How to horizontally align two UILabel (with fixed and variable width)


I have been facing issues horizontally aligning two UILabel and one UIImageView like this:

enter image description here

enter image description here

First label has variable width, can be truncated if long. Second label has fixed width, it should always be aligned to right of UIImageView. It should never go off screen. UIImageView is aligned to right of first label.

I have tried embedding them in horizontal UIStackView but the image + second label always aligns to end of cell. Got the same issue when trying without UIStackView. Please help.


Solution

  • You can embed both label and horizontal StackView into another horizontal stack view. Then, you'd need to set the dynamic width Label's Content Compression Resistance Priority (you can find this property at the bottom of the Size Inspector), to be smaller in order for it to shrink.

    Then on the container StackView (the one that contains all views), you'd need to set constrains to top, bottom, leading to 0 to the superview and the trailing to be greater than or equal to 0, for it to not take all space of the superview, but at the same time not get offset if the content is too wide.

    truncated :abel non truncated label

    I hope that is clear enough!