Dynamic constraints could be efficient and powerful if we get it work correctly. In other words, we need to make sure:

  • Do the deactivation/activation of constraints at the right place.
  • Try to avoid frequent view hierarchy changes (addSubview, removeFromSuperview).
  • Make sure active constraints don’t have conflicts.

Let’s dive into details of the three aspects:

Do the deactivation/activation of constraints at the right place:

For a view, `updateConstraints` is where the system gets the constraints for subviews and is efficient to apply constraint changes. To trigger `updateConstraints`, call `setNeedsUpdateConstraints` wherever the constraints need to be changed.

Try to avoid frequent view hierarchy changes (addSubview, removeFromSuperview):

Frequent view hierarchy changes requires recalculation of the layout, which is not efficient for displaying the views, and could cause update of the view not visually smooth.

Make sure active constraints don’t conflict:

Although iOS automatically deactivating conflicted constraints based on some magic in the system, it’s better to not contain conflicted constraints in the first place. Because older iOS versions may not be as intelligent as the newer ones dealing with constraints conflicts, and it could results in unexpected layout.