Search code examples
iosswiftautolayoutconstraintsnslayoutconstraint

Autolayout and linear equation


I'm trying to push my iOS development learning a little bit further by taking a look into auto layout and linear equation y = m.x + b.

Here is a simple exercise that I'm using : I have the SafeArea Viewand I added a greeView just above it. and I marked the four constraints that I'm interested in (#1 for the the top constraint, #2 for the Trailing one, #3 for the bottom one and #4 for the Leading constraint)

enter image description here

So, by applying the linear equation for the first one for example, it would be :

(1) : greenView.Top = 1.safeArea.top + 20

but apparently for the second constraint it's not :

(2) : greenView.Trailing = 1.safeArea.Trailing + 20

but instead, it should be :

(2) : safeArea.Trailing = 1.greenArea.Trailing + 20

I think I'm missing something to understand the logic behind the alignment of the 2nd constraint. Any hints please ? Thank you


Solution

  • There need to be some implicit order for the flow of constraints so that you know what "before" and "after" means.

    Apple has chosen top to bottom, leading (left in a LTR locale) to trailing (right).

    You want the trailing edge of the green view to be 20 "before" the trailing edge of the superview.

    There are two ways to specify this; as you have in (3) where the constraint says that the superview trailing is 20 more than the green trailing.

    You could also say greenView.trailing = 1.safeArea.trailing-20 to get the result you want.

    If you have the constraint as per (2) then the green view would be 20 off the right edge of the screen.