In UIKit, how do a UIStackView's axis, distribution, alignment and spacing place a trip card's two side-by-side buttons, and when is fillEqually better than fill?
answer
- along the axis versus across it
- defaults: horizontal, fill, fill, zero
- fill leans on hugging and resistance
- equal widths ignore title length
- removing an arranged view keeps it
basics
~20 sAxis picks a row or a column, distribution sizes views along it, alignment places them across it, and spacing sets the gaps. fill sizes buttons from their intrinsic widths and priorities; fillEqually gives both the same width whatever their titles.
solid answer
~40 sA `UIStackView` lays out its `arrangedSubviews` with Auto Layout. `axis` makes a row (`.horizontal`, the default) or a column; `distribution` sizes views **along** the axis; `alignment` places them **across** it; `spacing` sets the gap. The defaults are `.fill`, `.fill` and `0`. With `.fill`, the buttons keep their intrinsic widths and any extra or missing space goes by their hugging or compression resistance, falling back to arrangement order when that is ambiguous. With `.fillEqually`, both buttons get the same width, so "Cancel trip" and "Contact driver" read as a matched pair. You position the stack itself with constraints and leave the arranged subviews' `translatesAutoresizingMaskIntoConstraints` alone. Hiding a button with `isHidden` collapses its slot, but `removeArrangedSubview(_:)` alone leaves it on screen as an unmanaged subview.
code
swift · 21 linesimport UIKit
@MainActor
func makeTripActions() -> UIStackView {
var cancel = UIButton.Configuration.bordered()
cancel.title = "Cancel trip"
var contact = UIButton.Configuration.filled()
contact.title = "Contact driver"
let stack = UIStackView(arrangedSubviews: [
UIButton(configuration: cancel),
UIButton(configuration: contact)
])
stack.axis = .horizontal // the default
stack.distribution = .fillEqually // both buttons get the same width
stack.alignment = .center // each keeps its own height
stack.spacing = 12
// Position the stack itself; never touch its arranged subviews' flag.
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}go deeper
Recall what each of the four properties controls and their defaults: horizontal, fill, fill and zero spacing.
Explain how each distribution treats spare and missing space, why fill depends on hugging and resistance, and how isHidden collapses a slot.
Spot the stack traps in review: a removed arranged view still on screen, a fixed width fighting fillEqually, and code touching arranged views' autoresizing flag.
Weigh where stack views help a team and where deeply nested stacks hide layout intent, and set a guideline for which to reach for first.
## What a stack view is `UIStackView` (iOS 9) is a container that arranges the views in its `arrangedSubviews` array in a row or a column. The header calls it a non-rendering subclass of `UIView`: its job is to create and maintain the Auto Layout constraints for its arranged views, so you write a handful of property settings instead of a dozen constraints. You are still responsible for the stack's own **position**, and optionally its size, with ordinary constraints. Four properties decide the layout: - **`axis`**: `.horizontal` (a row, the default) or `.vertical` (a column). - **`distribution`**: how arranged views are sized *along* the axis. Default `.fill`. - **`alignment`**: how they are placed *across* the axis. Default `.fill`. - **`spacing`**: the distance between adjacent views. Default `0`; negative values allow overlap, and `UIStackView.spacingUseSystem` asks for the system's standard spacing. ## Distribution: sizing along the axis Every distribution fits the first and last arranged views tightly to the stack's edges. They differ in how they handle space that is left over (underflow) or missing (overflow): | Distribution | What happens | |---|---| | `.fill` | views keep their intrinsic sizes where possible; extra or missing space goes by hugging and compression resistance priorities, then by arrangement order | | `.fillEqually` | all views get the same size, the largest intrinsic size when space allows; differences are shared equally | | `.fillProportionally` | extra or missing space is shared in proportion to each view's intrinsic size | | `.equalSpacing` | views keep their sizes; extra space becomes equal gaps | | `.equalCentering` | keeps equal centre-to-centre distances, with `spacing` as the minimum edge-to-edge gap | For the trip card's two buttons, `.fill` makes their widths follow their titles, and a long localized title can make one button visibly wider. `.fillEqually` ignores title length and gives a balanced pair, which is what most designs for side-by-side actions want. If one button must stay at its natural size and the other take the rest, `.fill` with a lower hugging priority on the stretching button is the tool. `spacing` is a strict gap for the fill distributions and a **minimum** for `.equalSpacing` and `.equalCentering`. `setCustomSpacing(_:after:)` (iOS 11) overrides the gap after one particular view. ## Alignment: placing across the axis In a horizontal stack, `alignment` acts vertically: 1. `.fill` stretches every view to the stack's height. 2. `.top` and `.bottom` (the same values as `.leading` and `.trailing`) pin views to one edge at their own height. 3. `.center` centres each view at its own height. 4. `.firstBaseline` and `.lastBaseline` line text up on its baseline; the header marks them valid for horizontal stacks only. Except for `.fill`, the stack uses each view's intrinsic size across the axis, so a button keeps its natural height under `.center`. ## Rules the stack enforces - Adding a view to `arrangedSubviews` also makes it a subview; calling `removeFromSuperview()` on it also removes it from `arrangedSubviews`. - `removeArrangedSubview(_:)` only stops the stack managing the view. The view remains a subview and is still drawn, but nothing positions it any more. Call `removeFromSuperview()` when you want it gone. - The order of `arrangedSubviews` is the on-screen order; the order of `subviews` is only the drawing order. - Changing an arranged view's `isHidden` updates the layout automatically, and the change can be animated inside an animation block. - Apple's documentation says not to change `translatesAutoresizingMaskIntoConstraints` on arranged subviews; the stack handles them. ## Adding your own constraints You can still constrain arranged views, for example a minimum button height. The documentation's rule of thumb: if a view's size along a dimension falls back to its intrinsic size, you can safely constrain that dimension. A fixed width on one button inside a `.fillEqually` row, by contrast, fights the stack's own equal-size constraints and, once the stack's width is pinned, produces a conflict. ## Nesting stacks Real cards rarely fit one stack. Apple's documentation shows the usual shape: a vertical stack whose rows are horizontal stacks. For the trip card that means a vertical stack holding the driver row (name and fare), a details row and the actions row from this question, each with its own distribution. Keep nesting shallow: two or three levels read clearly, while a deep tree of stacks makes it hard to see which priority or spacing produced a given gap.
- How do you hide the Contact driver button during a trip without leaving a gap?Set the button's `isHidden` to `true`. A stack view watches its arranged views' hidden state and re-lays out so the remaining button takes the space; wrapping the change in an animation block animates the collapse. Removing it with `removeArrangedSubview(_:)` alone would leave it on screen as an unmanaged subview.
- When would you choose equalSpacing over fillEqually for a row of buttons?When each button should keep its natural width and only the gaps should grow. `.equalSpacing` divides extra room equally between the views, while `.fillEqually` resizes the views themselves to one size.
- removeArrangedSubview(_:) removes the view from the screen as well.
- A stack view sizes and positions itself without any constraints of its own.
- Distribution controls the layout across the axis, alignment along it.
- Every arranged subview needs translatesAutoresizingMaskIntoConstraints set to false by hand.
- fillEqually sizes each button to its own title width.