How to layer views on top of each other using ZStack
About 2 min
How to layer views on top of each other using ZStack êŽë š
SwiftUI by Example
Back to Home
How to layer views on top of each other using ZStack | SwiftUI by Example
How to layer views on top of each other using ZStack
Updated for Xcode 15
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)
.foregroundStyle(.white)
}
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)
.foregroundStyle(.white)
}
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.
Similar solutionsâŠ
How to add Metal shaders to SwiftUI views using layer effects | SwiftUI by Example
How to add Metal shaders to SwiftUI views using layer effects
How to use images and other views as backgrounds | SwiftUI by Example
How to use images and other views as backgrounds
How to show different images and other views in light or dark mode | SwiftUI by Example
How to show different images and other views in light or dark mode
How to hide the home indicator and other system UI | SwiftUI by Example
How to hide the home indicator and other system UI
How to hide the tab bar, navigation bar, or other toolbars | SwiftUI by Example
How to hide the tab bar, navigation bar, or other toolbars