Skip to main content

How to change the order of view layering using Z index

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to change the order of view layering using Z index 관련

SwiftUI by Example

Back to Home

How to change the order of view layering using Z index | SwiftUI by Example

How to change the order of view layering using Z index

Updated for Xcode 15

By default, SwiftUI's ZStack layers its views using the painter's algorithm to decide depth of views: whatever you put into the ZStack first is drawn first, then subsequent views are layered over it.

While this is often what you want, sometimes you need more control – you might want to push one view behind another while your app runs, for example, or perhaps bring one particular view to the front when it's tapped.

To do this you need to use the zIndex() modifier, which allows you to specify exactly how views should be layered inside a single ZStack. Views have a default Z index of 0, but you can provide positive or negative values that position them on top of or below other views respectively.

For example, this ZStack contains two overlapping rectangles, but the green rectangle will still be visible because it uses a Z index value of 1:

ZStack {
    Rectangle()
        .fill(.green)
        .frame(width: 50, height: 50)
        .zIndex(1)

    Rectangle()
        .fill(.red)
        .frame(width: 100, height: 100)
}

Download this as an Xcode projectopen in new window

A green square centered within a larger red square.
A green square centered within a larger red square.

Note

The zIndex() modifier only affects drawing order inside the current ZStack, so if you have two overlapping stacks you need to think about the Z index of the stacks as well as the views inside the stacks.

Similar solutions…
Adding items to an order with @EnvironmentObject | SwiftUI by Example

Adding items to an order with @EnvironmentObject
How to find which data change is causing a SwiftUI view to update | SwiftUI by Example

How to find which data change is causing a SwiftUI view to update
How to dynamically change between VStack and HStack | SwiftUI by Example

How to dynamically change between VStack and HStack
How to change the background color of List, TextEditor, and more | SwiftUI by Example

How to change the background color of List, TextEditor, and more
How to change the tint color for individual list rows | SwiftUI by Example

How to change the tint color for individual list rows

이찬희 (MarkiiimarK)
Never Stop Learning.