Nested UIStackViews Broken Constraints

Alex Popov picture Alex Popov · Oct 12, 2015 · Viewed 16.8k times · Source

I have a complex view hierarchy, built in Interface Builder, with nested UIStackViews. I get "unsatisfiable constraints" notices every time I hide some of my inner stackviews. I've tracked it down to this:

(
    "<NSLayoutConstraint:0x1396632d0 'UISV-canvas-connection' UIStackView:0x1392c5020.top == UILabel:0x13960cd30'Also available on iBooks'.top>",
    "<NSLayoutConstraint:0x139663470 'UISV-canvas-connection' V:[UIButton:0x139554f80]-(0)-|   (Names: '|':UIStackView:0x1392c5020 )>",
    "<NSLayoutConstraint:0x139552350 'UISV-hiding' V:[UIStackView:0x1392c5020(0)]>",
    "<NSLayoutConstraint:0x139663890 'UISV-spacing' V:[UILabel:0x13960cd30'Also available on iBooks']-(8)-[UIButton:0x139554f80]>"
)

Specifically, the UISV-spacing constraint: when hiding a UIStackView its high constraint gets a 0 constant, but that seems to clash with the inner stackview's spacing constraint: it requires 8 points between my Label and Button, which is irreconcilable with the hiding constraint and so the constraints crash.

Is there a way around this? I've tried recursively hiding all the inner StackViews of the hidden stack view, but that results in strange animations where content floats up out of the screen, and causes severe FPS drops to boot, while still not fixing the problem.

Answer

Senseful picture Senseful · Jul 7, 2016

This is a known problem with hiding nested stack views.

There are essentially 3 solutions to this problem:

  1. Change the spacing to 0, but then you'll need to remember the previous spacing value.
  2. Call innerStackView.removeFromSuperview(), but then you'll need to remember where to insert the stack view.
  3. Wrap the stack view in a UIView with at least one 999 constraint. E.g. top@1000, leading@1000, trailing@1000, bottom@999.

The 3rd option is the best in my opinion. For more information about this problem, why it happens, the different solutions, and how to implement solution 3, see my answer to a similar question.