Skip to content
DeveloperMemos

How to Use Spacing in SwiftUI VStack and HStack

SwiftUI, VStack, HStack, Spacing1 min read

Spacing in SwiftUI is a crucial aspect of layout design. SwiftUI provides two main containers for building layouts: VStack (vertical stack) and HStack (horizontal stack). Both of these containers allow us to arrange views in a stack, either vertically or horizontally, and specify the spacing between each view. In this article, we'll discuss how to use spacing in a VStack and HStack in SwiftUI.

Using Spacing in a VStack

A VStack is a vertical stack container that arranges its children in a vertical line. We can use the spacing parameter to specify the amount of space between each view in the stack. The following example shows how to use a VStack with a spacing of 20 points:

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

In this example, the three text views are arranged vertically, with a 20-point space between each view. The spacing parameter can also be used to adjust the space between the views dynamically, based on the size of the device or the amount of content in the views.

Using Spacing in an HStack

An HStack is a horizontal stack container that arranges its children in a horizontal line. We can use the spacing parameter in the same way as a VStack to specify the amount of space between each view in the stack. The following example shows how to use an HStack with a spacing of 20 points:

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

In this example, the three text views are arranged horizontally, with a 20-point space between each view.

Conclusion

In SwiftUI, the VStack and HStack containers are essential components for building layouts. The spacing parameter allows us to specify the amount of space between each view in the stack, providing greater control over the appearance and layout of our user interface. With this information, you can create professional-looking layouts with ease in your SwiftUI projects.