Search code examples
iosautolayout

when using constraints in ios autolayout, are there benefits to shorter constraint chains?


For example, when I want to make the leading value of 10 different UI elements match, should I be constraining 9 of them to the first item's leading value, or should I create a chain 1 -> 2 -> 3 -> 4 -> 5 -> 6 ...etc.

I was wondering about the performance differences and whether I should prefer one for maintenance reasons.


Solution

  • It's very difficult to answer an abstract question.

    If you want the leading of 10 UI elements to match...

    First, you're almost certainly better off putting them in a UIStackView... you constrain the stack view's leading and you're done.

    Second, if there is a reason you don't want to (or can't) use a stack view, then the answer depends on what else you might be doing.

    Suppose you want element 3 "indented" 40-pts?

    • If they're all aligned to element 1, you only change the constant of element 3.
    • If they're "chained" you have to change the constants of elements 3 and 4.

    Suppose you want elements 5 through 10 "indented" 40-pts?

    • If they're all aligned to element 1, you have to change the constants of elements 5, 6, 7, 8, 9 and 10.
    • If they're "chained" you only change the constant of element 5.

    Suppose you want to "insert" an element between 3 and 4? Or remove element 6?

    Suppose any of the above - or any number of other possibilities - are "conditional" and factor into the alignment?

    As you can see, the preference of one over the other will depend on many things.