Search code examples
swiftxcode-storyboard

Relative layout. Constrain equation explanation


Reading about constrains in relative layout, I have found the following:

Mathematically, any constraint can be expressed using the following equation:

Y = multiplier * X + Constant

X and Y are attributes of views and can be either left, right, top, bottom, leading, trailing, width, height, centerX, centerY, or baseline.

Could someone explain this, please?


Solution

  • I guess explaining on example works best, so:

    Assume you have some view that is positioned in it's view controller so that it's 10 points from the left. That means it's leading is set to 10. Now, this view has child view that we want to pin to it's left side. So we set leading constraint to match parent leading. Assuming we set the constant of this constraint to 0 (no gap) and don't modify multiplier (default is 1) the left position of this view is set to:

    childLeading = parentLeading * multiplier + constant

    that is:

    childLeading = 10 * 1 + 0 = 10

    so the left side is of child view is in the same position as it's parent.

    Modifying constant of the constraint we move the child view more to the left f.e. constant set to 8 results in:

    childLeading = 10 * 1 + 8 = 18

    and in a result the view is positioned 8 points from its parent left edge.

    I guess you can follow this logic in case of multiplier (which is much less often used than constant)