Learn how to use HStack, VStack, ZStack with spacing and alignment – SwiftUI

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.

stack

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")
}

VStack

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")
}

HStack

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)

ZStack

Resources

About the Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like these