deimus
deimus

Reputation: 9875

NSLayoutConstraint Positioning proportionally

The parent view (green rectangle) contains many subviews.

Lets consider only for one subview it has horizontal position with x offset from 0.

And whenever the parent view's width is changed lets say with factor of a, I need the subview to be positioned with offset equal to a * x

enter image description here

As much I understood NSLayoutConstraint does not allow to set a contraint for red subview's attribute NSLayoutAttributeLeft based on containing green views width NSLayoutAttributeWidth.

Any suggestion/reference how to acheive proportional positioning like described by means of NSLayoutConstraint is welcomed.

Upvotes: 2

Views: 811

Answers (2)

rdelmar
rdelmar

Reputation: 104082

As you said, you cannot relate the left attribute of your subview with the width of the superview, but you can relate it to NSLayoutAttributeRight, which has the same value as the width. So you should be able to do it by using a multiplier (and 0 for the constant),

[_greenView addConstraint:[NSLayoutConstraint constraintWithItem:_redView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_greenView attribute:NSLayoutAttributeRight multiplier:.1 constant:0]];

Of course you need to do the calculation to figure out, based on the width of the green view, what the multiplier should be. So, in my example, the greenView was 200 points wide to start with, and I wanted the red view to be 20 points from the left, so I used 0.1 for the multiplier.

Upvotes: 1

Fogmeister
Fogmeister

Reputation: 77641

You won't be able to lay it out in Interface Builder but you can use the NSLayoutAttributeLeft on the super view in code.

This way you can give it a multiple which will keep the position correct when the superview is updated.

If that doesn't work you can use a "spacer" view.

So you will have them both in the green superview like this...

|[spacerView][redView] //using VFL

Then you can set the width of the spacer view proportionally to the width of the green view.

Just set the spacerView to hidden or give it an alpha of 0.0 so it doesn't show.

Upvotes: 2

Related Questions