NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to control spacing around individual views using padding   How to return different view types >

How to layer views on top of each other using ZStack

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.

For example, we could place a large image underneath some text like this:

ZStack() {
    Image("example-image")
    Text("Hacking with Swift")
        .font(.largeTitle)
        .background(Color.black)
        .foregroundColor(.white)
}

Like the other stack types, ZStack can be created with an alignment so that it doesn’t always center things inside itself:

ZStack(alignment: .leading) {
    Image("example-image")
    Text("Hacking with Swift")
        .font(.largeTitle)
        .background(Color.black)
        .foregroundColor(.white)
}

However, it doesn’t have a spacing property because it doesn’t really make sense.

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to control spacing around individual views using padding   How to return different view types >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>