Entrée 🍽 Configuring the Layout
When we layout views,
we’re accustomed to thinking in terms of origin and size.
Working with stack views, however, requires us to instead think in terms of main axis and cross axis.
Consider how a horizontally-oriented stack view works.
To determine the width and the x coordinate of the origin for each of its arranged subviews,
it refers to a set of properties that affect layout across the horizontal axis.
Likewise, to determine the height and the y coordinate,
it refers to another set of properties that affects the vertical axis.
The UIStackView class provides axis-specific properties to define the layout: distribution for the main axis, and alignment for the cross axis.
This pattern is shared among many modern implementations of stacking layouts.
For instance,
CSS flexbox uses justify-content for the main axis and align-items for the cross axis.
Though not all implementations follow this axis-based paradigm; Android’s LinearLayout, for example, uses gravity for item positioning and layout_weight for item sizing along both axes.
The Main Axis: Distribution
The position and size of arranged subviews along the main axis is affected in part by the value of the distribution property,
and in part by the sizing properties of the subviews themselves.
In practice, each distribution option will determine how space along the main axis is distributed between the subviews.
With all distributions,
save for fillEqually, the stack view attempts to find an optimal layout based on the intrinsic sizes of the arranged subviews.
When it can’t fill the available space, it stretches
the arranged subview with the the lowest content hugging priority.
When it can’t fit all the arranged subviews,
it shrinks the one with the lowest compression resistance priority.
If the arranged subviews share the same value for content hugging and compression resistance,
the algorithm will determine their priority based on their indices.
Some implementations such as CSS flexbox allow setting the weights for each subview manually,
using the flex-basis property.
In iOS, setting a custom proportional distribution requires additional constraints between the subviews.
With that out of the way, let’s take a look at the possible outcomes,
starting with the distributions that prioritize preserving the intrinsic content size of each arranged subview:
equalSpacing: The stack view gives every arranged subview its intrinsic size alongside the main axis, then introduces equally-sized paddings if there is extra space.