Search code examples
iosuiviewautolayoutnslayoutconstraint

iOS: layout constraint with hidden views


Say I have two views aligned to bottom:

V:[Label1]-10-[Label2]-20-|

There is 10 points spacing between Label1 and Label2, 20 points spacing between Label2 and bottom.

Now, in some cases, I need to hide Label2, and in this case, I want to have:

V:[Label1]-15-|

That is, with Label2 being hidden, Label1 has 15 points spacing to bottom.

I'm setting this up in storyboard, I'm thinking of making the 15 points spacing having lower priority and hide Label2 as needed, but it doesn't seem to work.

What is the best way to achieve this?

Thanks!


Solution

  • I'm setting this up in storyboard

    Basically, you can't. You will have to use code to manage these constraints. When you hide Label2, also swap out the first set of constraints and swap in the second ones. When you show Label2, also swap out the second set of constraints and swap in the first ones. This is perfectly standard procedure.

    In fact, I have an example project that effectively shows how to do exactly what you're describing:

    https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch01p032constraintSwapping/ConstraintSwapping/ViewController.swift

    As you can see, we configure in advance the constraints for when the view v2 is present and for when it is absent, and just swap them when we remove or reinsert v2.