Itay Bianco
Itay Bianco

Reputation: 747

iOS add constraint for bottom of view to container center

I am trying to add a constraint for a UIView in iOS7 for aligning the bottom or top of a view to the center of its containing view.

Example:
LabelViewContainer contains 2 labels: label1, and label2.
The 2 labels should be aligned to the LabelViewContainer's center: label1's bottom should be 3 pixels above the center, and label2's top should be 5 pixels below the center.
The constraints I see in xcode allow me only to align the center of the labels to the center of the container whereas I would actually want the bottom or top of the labels to be above or below the container's center.

The only solution i've found so far was to add another hidden view which is centered with the container, and has a size of 0. Then have constraints for the labels with leading/trailing spaces to the new view.
I was hoping there was another solution that doesn't require inflation of a dummy view.

EDIT:
the size of the label views is unknown.

Upvotes: 0

Views: 2523

Answers (1)

staticVoidMan
staticVoidMan

Reputation: 20254

Assumptions:

  • Two UILabels with height of 30 and width of 280 starting a x = 20

Now... Lets see how to tackle your case.

Step 1:

Place the UILabel anywhere you want


Step 2:

Select both UILabels and set these common constraints
Common Constraints


Step 3:

Select Top most UILabel

Since you want it 3px above the center, note that it's height is 30.
If it were at the center, the UILabel's center would be at the view's center and so... if you took it up by half it's height (of 15px) then it's bottom edge would be touching the center line.
Now, take it 3px higher and you have it 3px above the center line.

Hence you need it 18px higher than the center line.
Which means you need to specify a constant of 18 when aligning it to the center of the view.
You can do it so:

Label1 Constraint


Step 4

Select Top most UILabel
Update the frame to conform to this constraint.

Label1 Update frames


Step 5

Select the other UILabel

Since you want it 5px below the center, note that it's height is 30.
If it were at the center, the UILabel's center would be at the view's center and so... if you took it lower by half it's height (of 15px) then it's top edge would be touching the center line.
Now, take it 5px lower and you have it 5px below the center line.

Hence you need it 20px lower than the center line.
Which means you need to specify a constant of -20 when aligning it to the center of the view.
You can do it so:

Label2 Constraint


Step 6

Select other UILabel

Update the frame to conform to this constraint.

Label2 Update frame

Upvotes: 1

Related Questions