How to Use Alignments in SwiftUI — Z-Stack Alignment

Mark van Wijnen
7 min readApr 12, 2022

This is the third part in the ‘SwiftUI Layout System’ series and the fifth part in the subseries about ‘How to Use Alignments in SwiftUI’. In this part we will talk about how alignments work along the z-axis in a Z-Stack.

The SwiftUI Layout System

(More to come …)

Z-Stack Alignment

If you read the previous parts of the series you may have noticed that I used the H-Stack in all of the examples. This has been done on purpose to get you familiar with the fundamentals of the alignment process.

However, we can easily take the concept and apply it to the V-Stack with one exception. The H-Stack uses VerticalAlignment for vertical positioning along the y-axis but for the V-Stack we need to use HorizontalAlignment for horizontal positioning along the x-axis.

But how does this concept apply to a Z-Stack with its views positioned along the z-axis?

Before we answer that question we should know that a H-Stack positions its views next to each other, a V-Stack positions its views below each other and a Z-Stack positions its views on top of each other. This means that views in a Z-Stack are only depended on each other on the z-axis and we have flexibility on the horizontal (x-axis) and vertical (y-axis) positioning.

The size of the Z-Stack, just like the H and V-Stack, is the union of the bounds of its children where aligning the views across the y and x-axis will expand the size.

Now to answer the question. The Z-Stack simply uses Alignment, which takes both the HorizontalAlignment and the VerticalAlignment. The concept is the same except it maintains two alignment guides and compares both.

To look at this in practice, let’s build the layout below and see how the alignment process is applied.

--

--

Mark van Wijnen

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs