NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to change the order of view layering using Z index

Paul Hudson    @twostraws   

Updated for Xcode 12.5

By default, SwiftUI’s ZStack layers its views using the painter’s algorithm to decide depth of views: whatever you put into the ZStack first is drawn first, then subsequent views are layered over it.

While this is often what you want, sometimes you need more control – you might want to push one view behind another while your app runs, for example, or perhaps bring one particular view to the front when it’s tapped.

To do this you need to use the zIndex() modifier, which allows you to specify exactly how views should be layered inside a single ZStack. Views have a default Z index of 0, but you can provide positive or negative values that position them on top of or below other views respectively.

For example, this ZStack contains two overlapping rectangles, but the green rectangle will still be visible because it uses a Z index value of 1:

ZStack {
    Rectangle()
        .fill(Color.green)
        .frame(width: 50, height: 50)
        .zIndex(1)

    Rectangle()
        .fill(Color.red)
        .frame(width: 100, height: 100)
}

Note: The zIndex() modifier only affects drawing order inside the current ZStack. This means if you two overlapping stacks you need to think about the Z index of the stacks as well as the views inside the stacks.

Hacking with Swift is sponsored by ViRE

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Download on the App Store

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.