ximmyxiao
ximmyxiao

Reputation: 2811

How to understand auto layout constraint's first item & second Item?

If I use a tableView as a View's subView in xib. And the tableView is fully covered the View. but in the xib's attributor , i can see the two vertical constrains just added : the 1st constraint use tableView's top as first Item , superView's top as second item , But in the 2nd constraint, it show that superview's bottom was the first item , and the tableView's bottom was the second item . what is the reason of the xib to decide use who as the first item & second Item .

Upvotes: 9

Views: 5738

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90621

All constraints express a formula of the form:

firstItem.firstItemAttribute == secondItem.secondItemAttribute * multiplier + constant

(The relation could be <= or >=, too.)

Most often, the multiplier is 1, so drop that:

firstItem.firstItemAttribute == secondItem.secondItemAttribute + constant

It's usually easiest to think in terms of positive constants. So, something like:

view.Top == superview.Top + 20

makes sense. The view's top is 20 points below the superview's top. (In the coordinate system used by auto layout, Y increases down, so adding 20 points gives a position "below".)

You could switch the items around, but, if you want the same relationship, you'll need to negate the constant:

superview.Top == view.Top + -20

That -20 may make it harder to understand. By the way, Xcode will happily swap the two items and negate the constant for you. (If the multiplier weren't 1, the math gets a bit more complicated, but it's still possible.)

If you were to just swap the items around but not negate the constant, it would express a different relationship:

superview.Top == view.Top + 20

That would mean that the superview's top would be below the view's top. Or, rather, that the view would be positioned above the top of the superview and it's top would be clipped.

Now, constraints on the other end are most often expressed with items in the other order because you usually want the relationship to be the opposite. That is, you want the view's top to be below the superview's top, but you want the view's bottom to be above the superview's bottom. So, the constant is positive only when you arrange the items in the other order:

superview.Bottom == view.Bottom + 20

Upvotes: 24

Related Questions