When it comes to layering of views in SwiftUI, the VStack
layers views vertically, HStack
layers views horizontally while ZStack
layers views on top of each other, usually with the first view being drawn first and then subsequent views layered over it.
However, there are times when you want more control. Maybe you want to bring a view behind another view even though they are not arranged in that order within a ZStack
or maybe these views are not directly in a ZStack
but have an intermediary parent view that is not a ZStack
. To achieve this, you need to utilize the zIndex()
modifier.
The zIndex()
modifier helps to control the display order of overlapping views. It takes a value
parameter that represents the relative front-to-back ordering for a view and the default value is 0. This implies, a view with a greater zIndex
value would be displayed on top of views with lesser zIndex
value. Let’s see an example of this modifier in use.
In a previous article, I wrote on creating a simple dropdown using SwiftUI, with a sample as shown below:
So, imagine this is a form and there is a TextField next to the Dropdown, below is what is would look like:
This is not the desired behaviour. With the use of the zIndex()
modifier we can bring the Dropdown in front of the TextField.
VStack(spacing: 20) { DropdownSelector( placeholder: "Day of the week", options: options, onOptionSelected: { option in print(option) }) .padding(.horizontal) .zIndex(1) // <----------- Here Group { TextField("Full Address", text: $address) .font(.system(size: 14)) .padding(.horizontal) } .frame(width: .infinity, height: 45) .overlay( RoundedRectangle(cornerRadius: 5) .stroke(Color.gray, lineWidth: 1) ) .padding(.horizontal) }
In the block of code above, the Dropdown is given a zIndex
of 1, which is greater than the zIndex
of the TextField (default value of 0). This automatically brings the Dropdown in front of the TextField and gives the desired result, as shown below:
As you can see, the zIndex()
modifier is simple but really powerful and can help you achieve a lot when it comes to creation and arrangement of views in SwiftUI. Why don’t you give it a try?
Updated source code for the Dropdown, which includes the use of the zIndex()
modifier can be found here.
Cheers!
I am using your picker component, thanks! Super helpful. I am encountering the problem described here, where I have an HStack containing 2 Pickers which pushes down the following child within a Vstack. I can do a hack by offsetting the y axis on the preceding child, but I’d rather not.
Seems like setting the zindex of the following child to -1 does the trick!
But I still need to offset the child… to get it back up.