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?
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.
SwiftUI framework supports overlay for covering an existing image with any view such as image, shape, or text.
HStack positions views in a horizontal line, VStack positions them in a vertical line, and ZStack overlays views on top of one another.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With