SwiftUI Negative Padding Z order

Viewed 1691

So in swiftUI, you can use negative padding or negative spacing to put two elements of a VStack on top of each other.

But how exactly do you select which item goes on top? Negative padding ensures there is an overlap, but does not specify which view will be on the top of the overlap. So, how can I control which view will go on top?

2 Answers

What an interesting question!

From just a little experimentation, it seems like the View that is added last is the one that is closer to the front.

This arrangement shows half the screen in green and half in red:

VStack(spacing: 0) {
    Spacer()
    Color.green.padding(-20)
    Color.red.padding(0)
    Spacer()
}

However, in this one, the red view overlaps the green one:

VStack(spacing: 0) {
    Spacer()
    Color.green.padding(0)
    Color.red.padding(-20)
    Spacer()
}

Wishing one container you can change z-order by .zIndex modifier. By default it is 0 (Zero) for all views, so giving any positive values pushes modified view on very top, and any negative value puts the view at bottom.

VStack(spacing: 0) {
    Spacer()
    Color.green.padding(0).zIndex(1)           // << here !!
    Color.red.padding(-20)
    Spacer()
}
Related