Z Index in SwiftUI : Setting things in order.

DevTechie
DevTechie
Published in
3 min readSep 3, 2022

--

ZIndex is used to alter default overlapping order in layout views. View with higher zIndex value appears at the top. Default value for zIndex is zero.

When two views overlap, framework determines the order by zIndex value and if two values are same, views are placed in the order they appear in hierarchy.

Let’s start with an example.

struct DevTechieZindexExample: View {

var body: some View {
VStack(spacing: 50) {
Text("DevTechie.com")
.font(.largeTitle)
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(Color.mint.gradient)
.frame(width: 100, height: 100)
.offset(x: 20, y: 20)

RoundedRectangle(cornerRadius: 20)
.fill(Color.orange.gradient)
.frame(width: 100, height: 100)
.offset(x: -20, y: -20)

RoundedRectangle(cornerRadius: 20)
.fill(Color.indigo.gradient)
.frame(width: 100, height: 100)
.offset(x: 10, y: -40)
}
}
}
}

--

--