DevPrep

All topics › Auto Layout

UIStackView: how do distribution and alignment work, and where are the gotchas?

Junior PRO

The gist

UIStackView is a container that creates constraints for its arranged subviews along a single axis (axis) by itself. You only specify the position (and optionally the size) of the stack, and the layout inside is described by four properties: axis, distribution — how space is split along the axis, alignment — how items are placed across the axis, and spacing.

It is important to distinguish arrangedSubviews from subviews: addArrangedSubview adds the view to both lists, while addSubview only adds it to the hierarchy, and the stack does not lay such a view out (that's how backgrounds or decorations are added).

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