How to use ZStack to put views on top of other views in SwiftUI?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

If you want to place a view on top of another view(s), you need to use ZStack. The ZStack places each child view a higher z-axis value than the one before it. It simply means that later children are presented “on top” of the earlier child views. The very common use of Zstack is placing a test on top of a view.

Let’s place a text on top of a view –

ZStack {
  Capsule()
    .fill(Color.orange)
    .frame(height: 40)
  Text("Sign up").font(.title2)
}

The default ZStack alignment is center. ZStack doesn’t have a spacing property but you can offset() to move the position of child view.

Output

struct ContentView: View {
    var body: some View {
        ZStack {
            Capsule()
                .fill(Color.orange)
                .frame(height: 40)
            Text("Sign up").font(.title2)
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.