3

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 2

5

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()
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

First thanks for answering John. Yes I have found the same thing to be true. The thing is, I need the view that comes first to be vertically on top (it's a header). Would you have any idea on how I would switch the order I declare the views in but keep the same vertical order?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.