How to Use ZStack in SwiftUI: Layer Views Easily
In SwiftUI, use
ZStack to place views on top of each other in layers. It stacks child views along the z-axis, so the first view is at the back and the last is on top. This lets you create overlapping UI elements easily.Syntax
The ZStack groups views by layering them in the order they are declared. The first view is the bottom layer, and each following view is stacked above it.
Basic syntax:
ZStack {
View1()
View2()
View3()
}Each View inside the braces is a layer. You can add modifiers to position or style each layer.
swift
ZStack {
Text("Bottom")
Text("Middle")
Text("Top")
}Output
Three texts stacked exactly on top of each other, with "Top" visible above "Middle" and "Bottom".
Example
This example shows a colored circle with a smaller circle and text layered on top using ZStack. It demonstrates how views overlap and can be positioned.
swift
import SwiftUI struct ContentView: View { var body: some View { ZStack { Circle() .fill(Color.blue) .frame(width: 150, height: 150) Circle() .fill(Color.white) .frame(width: 100, height: 100) Text("Hello") .font(.title) .foregroundColor(.black) } } }
Output
A large blue circle with a smaller white circle centered on it, and the word "Hello" centered on top.
Common Pitfalls
One common mistake is forgetting that ZStack layers views exactly on top of each other, so if views have the same size and position, only the top one is visible.
Another issue is not using modifiers like .offset() or .padding() to separate layers visually.
swift
/* Wrong: views overlap fully, hiding bottom layers */ ZStack { Rectangle() .fill(Color.red) .frame(width: 100, height: 100) Rectangle() .fill(Color.green) .frame(width: 100, height: 100) } /* Right: offset second rectangle to see both */ ZStack { Rectangle() .fill(Color.red) .frame(width: 100, height: 100) Rectangle() .fill(Color.green) .frame(width: 100, height: 100) .offset(x: 20, y: 20) }
Output
Wrong: only green rectangle visible fully covering red.
Right: red rectangle visible behind green rectangle shifted diagonally.
Quick Reference
- ZStack: stacks views front to back.
- First child is bottom layer, last child is top layer.
- Use
.offset()or.padding()to separate layers. - Combine with
alignmentparameter to position layers inside the stack.
Key Takeaways
Use ZStack to layer views on top of each other along the z-axis in SwiftUI.
The first view is the bottom layer; each next view stacks above it.
Apply modifiers like .offset() to avoid views fully overlapping and hiding each other.
ZStack is useful for creating complex UI with overlapping elements like badges, backgrounds, or overlays.