FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to create stacks using VStack and HStack

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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 project

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 {

Download this as an Xcode project

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 {

Download this as an Xcode project

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

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.