UIStackView: Layouts Without Manual Constraints

A UIStackView is an invisible container that arranges views in a single column or row, saving you from writing manual layout constraints. It's ideal for toolbars or forms. The main footgun is forgetting it's non-rendering—you can't set its background color.
WHY IT EXISTS Writing Auto Layout constraints by hand is verbose and error-prone for simple, linear arrangements. Before UIStackView, creating a basic form required dozens of lines of code just to define the positional relationships between each field and button, making layouts difficult to build and maintain.
THE MENTAL MODEL Think of UIStackView as an invisible box that acts as a layout manager, not a visible UI element. You drop views into it, tell it whether to arrange them vertically or horizontally, and it automatically generates and manages all the underlying constraints to position and size them according to your rules.
HOW IT WORKS A UIStackView manages a collection of views in its arrangedSubviews array. Its behavior is controlled by four key properties: axis (either .horizontal or .vertical), distribution (how to size views along the axis, like fillEqually or equalSpacing), alignment (how to position views perpendicular to the axis, like center or fill), and spacing (the gap between elements). The stack view reads these properties and creates the constraints for you. You do not interact with these constraints directly.
WHEN TO USE IT Use UIStackView for any layout that is fundamentally linear, meaning views are arranged in a single row or column. It's perfect for creating forms, toolbars, rows in a settings screen, or a detail view showing a label next to its value. It should be your default choice for most simple arrangements.
WHEN NOT TO USE IT Avoid UIStackView for complex, non-linear layouts. It is not suitable for grids, overlapping views, or any arrangement that isn't a straight line. For those cases, you need to write custom Auto Layout constraints or use a more powerful tool like UICollectionView. Also, since it's a non-rendering class, if you need a background or border around the group of views, you must embed the UIStackView inside a regular UIView.
ONE CANONICAL EXAMPLE To build a login screen, you could use a vertical UIStackView. You would set its axis to .vertical and spacing to 12. Then, you would add a UITextField for an email, another UITextField for a password, and a UIButton for the "Log In" action. The stack view would automatically arrange these three elements vertically with 12 points of space between each.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.