Updated for Xcode 14.2
SwiftUI has a dedicated stack type for creating overlapping content, which is useful if you want to place some text over a picture for example. It’s called ZStack
, and it works identically to the other two stack types.
For example, we could place a large image underneath some text like this:
ZStack {
Image("niagara-falls")
Text("Hacking with Swift")
.font(.largeTitle)
.background(.black)
.foregroundColor(.white)
}
Download this as an Xcode project
Like the other stack types, ZStack
can be created with an alignment so that it doesn’t always center things inside itself:
ZStack(alignment: .leading) {
Image("niagara-falls")
Text("Hacking with Swift")
.font(.largeTitle)
.background(.black)
.foregroundColor(.white)
}
Download this as an Xcode project
However, it doesn’t have a spacing property because it doesn’t make sense. Instead, you should use the offset()
modifier as shown in How to adjust the position of a view using its offset.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.