Razor Storm
Razor Storm

Reputation: 12336

How to center 2 vertically stacked UILabels vertically

I have 2 UILabels that are stacked vertically:

+----------------------------+
|  +----------------------+  |
|  | blah blah blah       |  |
|  +----------------------+  |
|                            |
|  +----------------------+  |
|  | asdf fdsa            |  |
|  | asdfear aoeirhaleir  |  |
|  +----------------------+  |
+----------------------------+

The UIViews have their text loaded dynamically in runtime, so they may have anywhere from 1 to 3 rows of text. I want to align the two vertically after the text has been loaded. They should be vertically centered along their "center of mass".

How may I accomplish this?

Edit: Like this: enter image description here

Upvotes: 5

Views: 1704

Answers (3)

Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

Place the two labels in a container UIView. Constrain the labels' edges to the container's edges (except for the bottom of the top label and the top of the bottom label, which should be constrained to each other), then vertically center the container within your top-level view.

Your view hierarchy should look like this:

UIView rootView
  UIView containerView
    UILabel topLabel
    UILabel bottomLabel

With the following constraints:

|[topLabel]|
|[bottomLabel]|
V:|[topLabel][bottomLabel]|
|-[containerView]-|
[NSLayoutConstraint constraintWithFirstItem:containerView firstAttribute:NSLayoutConstraintAttributeCenterY relation:NSLayoutRelationEquals secondItem:rootView secondAttribute:NSLayoutConstraintAttributeCenterY multiplier:1 constant:0]

(You could specify all of these constraints in IB rather than code; it's just harder to describe IB constraints in a StackOverflow post.)

Update: In more recent versions of iOS, it's easier to put the labels in a vertical stack view rather than using a plain view and setting up the constraints inside it manually, but the technique is the same.

Upvotes: 5

Duncan C
Duncan C

Reputation: 131481

You could do this with IB. Make their height flexible based on content. Make the distance between them small and fixed. Then put a spacer view above and below, with the top one with a top constraint to the superview and a bottom constraint tied to the top text view. The bottom spacer should have a top constraint linked to the bottom text view, and a bottom constraint tied to the superview, all with space of zero.

Finally, make a height constraint that makes the height of the 2 spacer views equal.

Upvotes: 2

greymouser
greymouser

Reputation: 3181

Use Auto Layout -- via manual NSLayoutContraint's, Visual Format Language (VFL), or even through Xcode/IB -- to create constraints that keep the label's widths equal, their X-centers equal to the superview's X-center, and heights variable or somewhat related depending on your needs.

Apple's Auto Layout Guide.

Upvotes: 0

Related Questions