Introduction on ZStacks, VStacks & HStacks in SwiftUI
- lioneldude
- Jun 29
- 1 min read
ZStacks, VStacks, and HStacks serve as the fundamental components of containers in SwiftUI. They are among the initial concepts to understand when developing an app with SwiftUI.
From the documentation:
ZStack - A view that overlays its subviews, aligning them in both axes.
VStack - A view that arranges its subviews in a vertical line.
HStack - A view that arranges its subviews in a horizontal line.

In this example, I show how the layouts work. The code is as follows:

Beginning at the top, let's first utilize a ZStack. We aim to add a background at the bottom, so start with a basic Rectangle and fill it with a color of your choice. To allow the rectangle to extend beyond the iPhone's safe areas, apply the .ignoresSafeArea() modifier, which is commented out in this example. To illustrate the outlines of each container, a .border() modifier is applied with a color, aiding in visualization and useful for debugging layouts.
An outer VStack is then applied on top of the ZStack to encapsulate the contents inside.
This is followed by a HStack and two VStacks. Inside the HStack, there is a VStack and a cat Image. Within the VStack, there is an Image using the SF Symbol for a house and the text "Hello, world!"
The last two VStacks include an alignment inside the brackets to demonstrate how to align elements within the container.
This example illustrates how to use containers in SwiftUI.



Comments