ZStack
A view that overlays its subviews, aligning them in both axes.
Declaration
@frozen struct ZStack<Content> where Content : ViewMentioned in
Overview
The ZStack assigns each successive subview a higher z-axis value than the one before it, meaning later subviews appear “on top” of earlier ones.
The following example creates a ZStack of 100 x 100 point Rectangle views filled with one of six colors, offsetting each successive subview by 10 points so they don’t completely overlap:
let colors: [Color] =
[.red, .orange, .yellow, .green, .blue, .purple]
var body: some View {
ZStack {
ForEach(0..<colors.count) {
Rectangle()
.fill(colors[$0])
.frame(width: 100, height: 100)
.offset(x: CGFloat($0) * 10.0,
y: CGFloat($0) * 10.0)
}
}
}[Image]
The ZStack uses an Alignment to set the x- and y-axis coordinates of each subview, defaulting to a center alignment. In the following example, the ZStack uses a bottomLeading alignment to lay out two subviews, a red 100 x 50 point rectangle below, and a blue 50 x 100 point rectangle on top. Because of the alignment value, both rectangles share a bottom-left corner with the ZStack (in locales where left is the leading side).
var body: some View {
ZStack(alignment: .bottomLeading) {
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 50)
Rectangle()
.fill(Color.blue)
.frame(width:50, height: 100)
}
.border(Color.green, width: 1)
}[Image]
Topics
Creating a stack
Supporting symbols
Initializers
See Also
Layering views
Adding a background to your viewzIndex(_:)background(alignment:content:)background(_:ignoresSafeAreaEdges:)background(ignoresSafeAreaEdges:)background(_:in:fillStyle:)background(in:fillStyle:)overlay(alignment:content:)overlay(_:ignoresSafeAreaEdges:)overlay(_:in:fillStyle:)backgroundMaterialcontainerBackground(_:for:)containerBackground(for:alignment:content:)ContainerBackgroundPlacement