Search code examples
iosswiftpositionuilabel

How to center vertically labels in a view


I have 4 labels like this in a view:

enter image description here

The view hierarchy like this:

enter image description here

But if one of text in each label is empty, all of other labels should center vertically with the image.

For example: the albumDataLabel.text is empty, then userNameLabel, albumNameLabel, albumLocationLabel should center vertically with the image.

Somethings like this:

enter image description here

So how to do this, please point me to some approaches.


Solution

  • Since your 4 Labels are already in a view, you can set the labels' constraints to pin the first Label to the top, last Label the bottom and spacing in between to zero

    Then select the view(withLabels) and your ImageView to align their vertical centers

    Do not set a height value constraint for your labels nor the view

    When one of your labels have an empty string, the height is automatically set to zero and hence 'hidden' so the view(withLabels) will shrink in height. All can be done in the interface builder, no coding necessary, it is just a matter of autolayout.