Difference between a ZStack or using .overlay()
Asked Answered
S

1

45

What is the difference between using a ZStack versus using the .overlay() modifier.

Apple says:

ZStack = "A view that overlays its children, aligning them in both axes."

.overlay = "Layers a secondary view in front of this view."

Some examples:

ZStack(alignment: .bottom) {
    Image(systemName: "folder")
        .font(.system(size: 55, weight: .thin))
    Text("❤️")
}
Image(systemName: "folder")
    .font(.system(size: 55, weight: .thin))
    .overlay(Text("❤️"), alignment: .bottom)

Not considering code size, is there a distinct purpose where one must be used over the other?

Steeplechase answered 17/8, 2020 at 7:13 Comment(0)
P
69

In ZStack views are independent on each other and stack fits (if does not have own frame) to biggest view. Also order in ZStack can be modified by using .zIndex modifier. All views are in ZStack coordinate space.

In .overlay case the view inside overlay always bound to parent view and always above parent view (ie. zIndex does not play any role). Also overlaid views are in parent view coordinate space.

The most visible difference is if to make views different size and apply clipping, ie

struct TestZStack: View {
    var body: some View {
        ZStack(alignment: .bottom) {
            Image(systemName: "folder")
                .font(.system(size: 55, weight: .thin))
            Text("❤️").font(.system(size: 55, weight: .thin))
        }
        .clipped()
    }
}

gives demo 1

struct TestOverlay: View {
    var body: some View {
        Image(systemName: "folder")
            .font(.system(size: 55, weight: .thin))
            .overlay(Text("❤️").font(.system(size: 55, weight: .thin)), alignment: .bottom)
            .clipped()
    }
}

gives demo2

Phelan answered 17/8, 2020 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.