Learn how to use HStack, VStack, ZStack with spacing and alignment! Swiftui Tutorial

Stacks in SwiftUI are similar to the stack views in UIKit. By combining views in horizontal and vertical stacks, you can build complex user interfaces for your application. There are 3 types of stacks: HStack, VStack and ZStack.

Downloads

To follow this tutorial, you can download the source file, which will help you compare your progress.

VSTACK

The VStack allows you to stack views vertically, from top to bottom. You can further customize the view by adding alignment or spacing to the VStack.
VStack(alignment: .leading, spacing: 16) {
	Text("Hello, world!")
		.font(.title)
	Spacer()
	Text("Second line")
}

HSTACK

The HStack is used to stack views horizontally. Just like the VStack, you can set the alignment and space items.
HStack(alignment: .bottom, spacing: 16) {
	Text("Hello, world!")
		.font(.title)
	Spacer()
	Text("Second line")
}

SPACER

By default, stacks in SwiftUI will take the minimum space and align to the center. The Spacer is essential for pushing the content to use the maximum space. It can be useful for aligning elements as well.
HStack(alignment: .bottom, spacing: 16) {
	Text("Hello, world!")
		.font(.title)
	Spacer()
	Text("Second line")
}
.padding()
.frame(width: 320)

ZSTACK

ZStack is great for overlapping content. It stacks layers on top of each other, in a 3 dimentional plane. Since elements can float on top of each other, the alignment for ZStack will move all items at one.
ZStack(alignment: .topLeading) {
    Rectangle()
        .foregroundColor(.blue)
    Text("Hello, world!")
        .font(.title)
    Spacer()
    Text("Second line")
}
.padding()
.frame(width: 320)

More Projects

Group 6 CopyCreated with Sketch.

More Information?

Fill out your details and we will get back to you as soon as possible.