DevPrep

All topics › Auto Layout

How do you change and animate constraints: isActive, constant, layoutIfNeeded?

Middle PRO

The gist

There are three ways to change layout at runtime, from cheap to expensive: change the constant of a stored constraint, swap the priorities of two optional constraints, or deactivate one set and activate another. Recreating constraints on every change, especially in layoutSubviews, is an anti-pattern: it is constraint churn and extra work for the engine.

The animation is the same in all three cases: flush pending layout, change the constraints, and call layoutIfNeeded() on the common ancestor inside the animation block. What animates is the result of the layout pass, not the constraint itself.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store