Skip to main content

How to create stacks using VStack and HStack

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create stacks using VStack and HStack 관련

SwiftUI by Example

Back to Home

How to create stacks using VStack and HStack | SwiftUI by Example

How to create stacks using VStack and HStack

Updated for Xcode 15

Our SwiftUI content views must contain one or more views, which is the layout we want them to show. When we want more than one view on screen at a time you'll usually want to tell SwiftUI how to arrange them, and that's where stacks come in.

Stacks – equivalent to UIStackView in UIKit – come in three forms: horizontal (HStack), vertical (VStack) and depth-based (ZStack), with the latter being used when you want to place child views so they overlap.

Let's start with something simple. Here's one text view:

Text("Hello, world!")

Download this as an Xcode projectopen in new window

The words “Hello, world!” on a plain background.
The words “Hello, world!” on a plain background.

If we want to place another below, we can't just create a second text view and hope for the best – SwiftUI doesn't know how to arrange them.

Instead, we need to place it in a vertical stack so our text views are placed above each other:

VStack {
    Text("SwiftUI")
    Text("rocks")
}

Download this as an Xcode projectopen in new window

The text “SwiftUI” above the text “rocks”.
The text “SwiftUI” above the text “rocks”.

You'll notice that the vertical stack is placed at the center of the screen, with the labels also being centered and having some automatic space between them.

If you wanted the labels side by side horizontally, replace VStack with HStack like this:

HStack {
    Text("SwiftUI")
    Text("rocks")
}

Download this as an Xcode projectopen in new window

The text “SwiftUI” beside the text “rocks”.
The text “SwiftUI” beside the text “rocks”.
Similar solutions…
How to automatically switch between HStack and VStack based on size class | SwiftUI by Example

How to automatically switch between HStack and VStack based on size class
How to dynamically change between VStack and HStack | SwiftUI by Example

How to dynamically change between VStack and HStack
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
Composing views to create a list row | SwiftUI by Example

Composing views to create a list row

이찬희 (MarkiiimarK)
Never Stop Learning.