Twitter khuong291
Twitter khuong291

Reputation: 11702

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.

Upvotes: 0

Views: 1037

Answers (3)

Zayne ZH
Zayne ZH

Reputation: 406

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.

Upvotes: 2

Carlo
Carlo

Reputation: 835

1) for your userNameLabel:

userNameLabel.leftAnchor.constraintEqualToAnchor(imageView.rightAnchor, constant: 10).active = true
                userNameLabel.topAnchor.constraintEqualToAnchor(self.topAnchor, constant: 50).active = true
                userNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
                userNameLabel.heightAnchor.constraintEqualToConstant(30).active = true

2) for your albumNameLabel:

albumNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
                albumNameLabel.heightAnchor.constraintEqualToConstant(30).active = true
                albumNameLabel.topAnchor.constraintEqualToAnchor(userNameLabel.bottomAnchor, constant: 5).active = true
                albumNameLabel.leftAnchor.constraintEqualToAnchor(imageView.leftAnchor, constant: 10).active = true

3) remember this:

self.addSubview(userNameLabel)
self.addSubview(albumNameLabel)

And go on in this way to all elements in your View.

Upvotes: 0

Ketan Parmar
Ketan Parmar

Reputation: 27448

  • Set height constraint for every label and which label have not text make it's height zero(from outlet of height constraint by setting constant to 0) at runtime.
  • Your constraint should be in linear hierarchy like first label's top should be pinned with it's supper view's top and last label's bottom should be pinned with superview's bottom and each and every label's bottom should be pinned with top of below label.
  • then you should set height constraint for view that contains all labels with constant (>=) of minimum height(least height of your view).
  • and centered vertically that view with your image view.

you can do this kind of setup!!

Upvotes: 3

Related Questions