Reputation: 5525
I just read few information about how to manipulates constraints number programatically, but I think I need to see it visually using Xcode. So I decided to put a UIView like this and see what's going on with Constraints :
automatically it will create 4 constraints :
after modifying the number, I got what's the meaning of all this. there we have 2 vertical space and 2 horizontal space. but let's focus on vertical first...
one of vertical space measured from top of the screen (superview, I guess), I give this number 30. and other vertical space measured from the bottom, I give -50.
now, when it turns into code, I really don't understand how to give this 2 numbers. as far as I know, here's how to set constraint with code :
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:_screenView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:_container
attribute:NSLayoutAttributeHeight
multiplier:20
constant:200];
[_screenView addConstraint: myConstraint];
let's assume _screenView
is a superview and _container
is UIView placed on top of it. I have 3 questions :
NSLayoutConstraint
?[_screenView addConstraint: myConstraint];
twice?multiplier
used for? because I don't see that option in storyboard.thank you very much.
Upvotes: 0
Views: 5983
Reputation: 1625
I think it's important to think of this formula from Apple's Auto Layout Guide when working with constraints:
y = m*x + b, where:
y and x are attributes of views.
m and b are floating point values.
You can think the constraint for the top of _container like this:
_containter.top = m*_screenView.top + b
When you are creating a constraint using NSLayoutConstraint constraintWithItem:...
the multiplier argument is "m" and constant is "b" in this formula. To create a constraint that keeps the top of _container 30 points below the top of _screenView you would do this:
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:_container
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_screenView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:30.0];
The bottom constraint would be:
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:_container
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_screenView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-50.0];
Also keep in mind that in the UIKit coordinate system X values go up from left to right and Y values go up from top to bottom. In other words, 0,0 is at the top-left of screen and the values go up from there.
If you want to create the four contraints you show above you will have to create them all individually. You could also use the constraintsWithVisualFormat:options:metrics:views:
method of NSLayoutConstraint to make multiple at once. I find it more clear to write them out the way I did above.
Upvotes: 6