← Back to archive

Development · SwiftUI

Layouts with VStack, HStack, and ZStack

Arrange child views vertically, horizontally, or in layers, and control their alignment and spacing.

Read the Korean original on Velog ↗English translation

Development archive cover

SwiftUI layout starts with deciding how children relate to one another. Applying the three stack types to the same elements makes their direction and alignment differences clear.

HStack

Arranges children horizontally. Choose their vertical alignment and the spacing between adjacent views.

HStack (alignment: .bottom, spacing: 10) { // Bottom alignment with spacing of 10
	Circle() // Left
		.fill(Color.red)
		.frame(width: 150, height: 150)
	Circle() // Center
		.fill(Color.green)
		.frame(width: 100, height: 100)
	Circle() // Right
		.fill(Color.blue)
		.frame(width: 50, height: 50)
}

VStack

Arranges children vertically. Choose their horizontal alignment and the spacing between adjacent views.

VStack (alignment: .leading, spacing: 10) { // Leading alignment with spacing of 10
	Circle() // Top
		.fill(Color.red)
		.frame(width: 150, height: 150)
	Circle() // Center
		.fill(Color.green)
		.frame(width: 100, height: 100)
	Circle() // Bottom
		.fill(Color.blue)
		.frame(width: 50, height: 50)
}

ZStack

Layers children in depth order. Its alignment controls both horizontal and vertical positioning.

ZStack (alignment: .topLeading) { // Top-leading alignment
	Circle() // Trailing edge
		.fill(Color.red)
		.frame(width: 150, height: 150)
	Circle() // Center
		.fill(Color.green)
		.frame(width: 100, height: 100)
	Circle() // Leading edge
		.fill(Color.blue)
		.frame(width: 50, height: 50)
}
← Back to archive