How to control the display order of overlapping views in SwiftUI

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:

screencast 2021 05 09 12 51 32

So, imagine this is a form and there is a TextField next to the Dropdown, below is what is would look like:

Dropdown overlapped by TextField

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:

Dropdown with TextField and zIndex

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!