Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 639
Razor Storm Avatar asked Feb 19 '14 02:02

Razor Storm


2 Answers

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.

like image 101
Becca Royal-Gordon Avatar answered Sep 22 '22 03:09

Becca Royal-Gordon


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.

like image 27
Duncan C Avatar answered Sep 23 '22 03:09

Duncan C