ZStack is used to layout a view that overlays its subviews, aligning them in z-axis. ZStack overlays its subviews by assigning each successive subview a higher z-axis value then the one before it. This means that at the end subviews appear on top of each other.
Let’s look at an example. We will create 10 cards stacked over each other using ZStack.
By default, ZStack aligns its views at the center but we can change the alignment by passing alignment value. Let’s update our example to include alignment.
Notice that the safeArea at the bottom and at the top is not covered by the background color. By default, safeArea is honored but we can change that with the help of .ignoresSafeArea() modifier.
Another use case for ZStack is to have a Fast Action Button(FAB) control on the view.
struct DevTechieZStack: View {
let dtCourses = [
"Master SwiftUI 4 by Example",
"Build Photo Gallery App in SwiftUI",
"Introdution to MapKit in SwiftUI",
"Food Recipes app in SwiftUI",
"Machine Learning in iOS",
"Build Strava Clone in UIKit",
"Build DisneyPlus Clone in SwiftUI",
"Maps in SwiftUI",
"What's new in SwiftUI 4",
"Shoe Shopping app with Apple Pay in SwiftUI",
"Top Destinations App in SwiftUI",
"HealthKit integration in SwiftUI",
"Build DevTechie Video Course wth AVPlayer and SwiftUI",
"Let's Build Pantry App With Firebase and SwiftUI",
"iOS 15 Widgets using WidgetKit and SwiftUI",
"Goals app in SwiftUI and Firebase"
]
var body: some View {
NavigationStack {
ZStack(alignment: .bottomTrailing) {
List(dtCourses, id: \.self) { course in
Text(course)
.font(.title3)
}
Button {
print("Button pressed")
} label: {
Image(systemName: "plus.circle.fill")
.resizable()
.frame(width: 50, height: 50)
}
.padding([.trailing, .bottom], 10)
}
.navigationTitle("DevTechie Courses")
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to follow 😍. Also subscribe our newsletter at https://www.devtechie.com