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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With