Skip to content
DeveloperMemos

Using VStack in SwiftUI

SwiftUI, VStack, Layout1 min read

VStack is a container view in SwiftUI that arranges its child views vertically. It is part of the SwiftUI framework and can be used to create user interfaces for iOS, macOS, watchOS, and tvOS.

To use VStack in your SwiftUI app, you can simply add it to your view hierarchy and then add the views that you want to stack vertically inside it. For example:

1VStack {
2 Text("First view")
3 Text("Second view")
4 Text("Third view")
5}

This will create a vertical stack containing three text views, with the first view at the top, the second view in the middle, and the third view at the bottom.

You can also customize the layout of the VStack by using various properties and methods provided by the VStack type. For example, you can use the spacing property to add space between the stacked views, like this:

1VStack(spacing: 20) {
2 Text("First view")
3 Text("Second view")
4 Text("Third view")
5}

This will add a 20-point space between the first and second views, and another 20-point space between the second and third views.

Another useful property is alignment, which allows you to specify the alignment of the stacked views within the VStack. For example, you can use the .leading alignment to align the views to the leading edge of the VStack, like this:

1VStack(alignment: .leading) {
2 Text("First view")
3 Text("Second view")
4 Text("Third view")
5}

You can also use the .trailing alignment to align the views to the trailing edge of the VStack, or the .center alignment to center the views within the VStack.

In addition to these properties, VStack also provides several methods that you can use to customize its layout. For example, you can use the frame() method to specify the size of the VStack, or the padding() method to add padding around the edges of the VStack.

Here's an example that uses both the frame() and padding() methods to customize the layout of a VStack:

1VStack {
2 Text("First view")
3 Text("Second view")
4 Text("Third view")
5}
6.frame(width: 300, height: 200)
7.padding(20)

This will create a VStack that is 300 points wide and 200 points tall, with a 20-point padding around the edges.

In summary, VStack is a powerful and versatile container view in SwiftUI that allows you to arrange views vertically in your user interfaces. Whether you want to stack views vertically with equal spacing, align them to the leading or trailing edge of the VStack, or customize the size and padding of the VStack, VStack has you covered.