Skip to main content

How to layer views on top of each other using ZStack

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

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)
}

Download this as an Xcode projectopen in new window

“Hacking with Swift” in white text on a black rectangle, centered over an image of Niagara Falls.
“Hacking with Swift” in white text on a black rectangle, centered over an image of Niagara Falls.

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)
}

Download this as an Xcode projectopen in new window

“Hacking with Swift” in white text on a black rectangle, touching the left edge of an image of Niagara Falls.
“Hacking with Swift” in white text on a black rectangle, touching the left edge of an image of Niagara Falls.

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 a backgrounds | SwiftUI by Example

How to use images and other views as a 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

이찬희 (MarkiiimarK)
Never Stop Learning.