Alin Golumbeanu
Alin Golumbeanu

Reputation: 599

How to use auto-layout to move a UILabel relative to a UIView height?

I can't figure out how to use auto-layout to reposition a UILabel relative to a UIView height.

Example: If a UIView has a height of 50 points, and a UILabel is positioned at 10 points from the top and 30 points from the bottom, enter image description here

how to maintain the UILabel position ratio if the UIView changes to a height of 70 points, more exactly to obtain 20 points from the top and 40 points to the bottom for the UILabel using auto-layout.

enter image description here

Upvotes: 0

Views: 380

Answers (2)

Sega-Zero
Sega-Zero

Reputation: 3017

Assume your label height is 20. Set top label constraint to superview's centerY like this: constraint screenshot

With this config the label topY will be 10 for superview height of 50 and 20 with superview height of 70. Alternatively you may use the conception of spacer views - an invisible UIView instance that is used just for layout adjusting, which is absolutely normal way of doing layout. In iOS9 Apple introduce new UILayoutGuide class which basically do the same thing, but does not consume any resources, like layers etc.

Upvotes: 2

Ville Rinne
Ville Rinne

Reputation: 821

The only solution to this that I am aware of is to add a separate "spacing" view that is hidden. So if you want to maintain you relative 20% spacing on top you can add a hidden view that has 10px height and is at x: 0 y:0 relative to the superview. You then set the height of that view to be relative to the superview by setting the multiplier as 10/50 (height of your spacing view divided by the height of the superview).

Then you connect the vertical spacing of your test view to 0px of the spacing view. Once the layout changes the height of the invisible spacing view changes with the superview and the relateive Y position of your view is maintained.

I find it idiotic that I am reduced to doing this but I have not found another way that works in XCode 6.

Upvotes: 2

Related Questions