Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a ZStack or using .overlay()

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?

like image 858
Michael Ozeryansky Avatar asked Aug 17 '20 07:08

Michael Ozeryansky


People also ask

What is a ZStack?

Overview. The ZStack assigns each successive subview a higher z-axis value than the one before it, meaning later subviews appear “on top” of earlier ones.

What does overlay do in SwiftUI?

SwiftUI framework supports overlay for covering an existing image with any view such as image, shape, or text.

What is HStack and VStack?

HStack positions views in a horizontal line, VStack positions them in a vertical line, and ZStack overlays views on top of one another.

What is AZ stack SwiftUI?

SwiftUI has a dedicated stack type for creating overlapping content, which is useful if you want to place some text over a picture for example. It's called ZStack , and it works identically to the other two stack types.


1 Answers

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

like image 151
Asperi Avatar answered Sep 30 '22 03:09

Asperi