HStack
HStack is a layout container that arranges its children horizontally, in order of definition. If the children have different heights, it vertically aligns them as well. Note that HStack and VStack use the same layout algorithm, but with the axes swapped.
One of the unexpected effects we see above is that the view initially renders with the text on two lines, even though there's enough space to render the text without word wrapping. Without going into too much detail yet, this happens because of the way the stack proposes sizes to its children. One helpful thing to keep in mind is that, in principle, stacks try to distribute their space as evenly as possible.
Stacks always start by ordering their children according to flexibility. The horizontal flexibility is the difference between the widest and narrowest possible width of a view. For each child, the stack computes the flexibility by proposing a zero width and an infinite width. It then subtracts the two resulting widths from each other, resulting in the child's flexibility. In our example, the text is the least flexible view, so the stack proposes a third of its available space. This isn't enough to fully render the text on a single line. In the following interactive example, we can step through the algorithm of an HStack.
Here's the same example, but we've given the text a higher layout priority. Now the text is rendered at its ideal size.
HStack { RoundedRectangle(cornerRadius: 8) .fill(Color.blue) Text("Hello, world").layoutPriority(1) RoundedRectangle(cornerRadius: 8) .fill(Color.green) }
Using a higher layout priority causes the stack to propose the entire remaining width to the first group (containing just the text) before proceeding with the second group (the two rectangles). If a group contains views with different flexibilities, the views are sorted within their group.
Alignment
After all views have a horizontal position, the stack aligns the views vertically. It queries the relevant alignment guide for each child and makes sure the returned values (in terms of the child's local coordinate system) are on a single horizontal line. Note that due to the way the stack proposes, the stack might become taller than its own proposed size (for example, when using first text baseline alignment).