NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to use images and other views as a backgrounds   How to customize stack layouts with alignment and spacing >

How to create stacks using VStack and HStack

Our SwiftUI content views must return one view, which is the view we want them to show. When we want more than one view on screen at a time we need 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("SwiftUI")

If we want to place another below, we can’t just write this:

var body: some View {
    Text("SwiftUI")
    Text("rocks")
}

Remember, we need to return precisely one View, so that code won’t work.

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

VStack {
    Text("SwiftUI")
    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")
}

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to use images and other views as a backgrounds   How to customize stack layouts with alignment and spacing >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>