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.
SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.