Stacks in SwiftUI Fast AF

Swift Fast AF
2 min readDec 20, 2022

--

HStacks and VStacks are two of the most useful layout tools in SwiftUI. They allow developers to easily stack views horizontally or vertically, making it easy to build complex user interfaces. In this tutorial, we’ll go over how to use HStacks and VStacks in SwiftUI, including some of their most useful features and how to customize them.

First, let’s start with a basic example of how to use an HStack. An HStack is a horizontal stack of views, and it is defined using the HStack SwiftUI view. Here is a simple example of how to use an HStack to stack three views horizontally:

HStack {
Text("First View")
Text("Second View")
Text("Third View")
}

This will create an HStack with three views, each containing a different piece of text. The views will be stacked horizontally, with the first view on the left, the second view in the middle, and the third view on the right.

Now let’s look at some of the customization options available for HStacks. One useful feature is the ability to add padding to the views within the stack. This can be done using the padding() modifier, which allows you to specify the amount of padding to add to each side of the view. Here is an example of how to add padding to the views in an HStack:

HStack {
Text("First View")
.padding()
Text("Second View")
.padding()
Text("Third View")
.padding()
}

In addition to padding, you can also use the spacing() modifier to specify the amount of space between the views in the stack. This can be useful for creating more visually appealing layouts. Here is an example of how to use the spacing() modifier with an HStack:

HStack {
Text("First View")
.padding()
Text("Second View")
.padding()
Text("Third View")
.padding()
}
.spacing(10)

Now let’s move on to VStacks, which are similar to HStacks but stack views vertically instead of horizontally. The syntax for creating a VStack is the same as for an HStack, except that you use the VStack view instead of the HStack view. Here is an example of how to create a VStack:

VStack {
Text("First View")
Text("Second View")
Text("Third View")
}

Just like with HStacks, you can also customize VStacks by using the padding() and spacing() modifiers. Here is an example of how to use these modifiers with a VStack:

VStack {
Text("First View")
.padding()
Text("Second View")
.padding()
Text("Third View")
.padding()
}
.spacing(10)

In conclusion, HStacks and VStacks are powerful tools in SwiftUI for building complex user interfaces. They allow you to stack views horizontally or vertically, and provide a range of customization options such as padding and spacing. With a little practice, you’ll be able to use HStacks and VStacks to create beautiful and functional layouts in your SwiftUI apps.

References:

--

--