Search code examples
swiftautolayoutuilabel

Swift: Auto Layout - Columns of Text - removing trailing and leading warnings


enter image description here

I have two columns of text. The left is anchored top, left and bottom and the righthand side conversely. This still generates leading and trailing warnings. How do I connect the two columns' rows to tell Auto Layout to just expand the space in between?


Solution

  • While YOU know exactly what text you're going to put into those labels, Storyboard / Interface Builder (IB) has no idea.

    So this looks great to you:

    enter image description here

    But... what happens if the "Date" text changes to "When do you want to get started?":

    enter image description here

    Because we haven't given a constraint between the two labels, they overlap.

    So, let's do the same thing on both "rows" but, add a Trailing-to-Leading constraint of 8 between the labels:

    enter image description here

    We've prevented the overlap but now we see a new problem (that IB will warn you about)... Which label should get compressed? IB (and auto-layout at run-time) will make its own decision, which may not be what you want, and which may be inconsistent between similar layouts.

    To fix that, we give a higher Content Compression Resistance Priority to the label we do not want compressed:

    enter image description here

    And here is the result - top "row" has the left-hand label at the default of 750, and the right-hand label at 751, and the bottom "row" has the left-hand label at 751, and the right-hand label at the default of 750:

    enter image description here

    It looks the same as "C" but we no longer have errors/warnings from IB.

    So, even if you know the text in your two columns will never be enough to overlap, IB is going to encourage you to provide enough constraints (and priority settings) to make sure you get exactly what you want.