Lab 082 – Using implicit glassBackgroundEffect with depth

We can use implicit display mode to show glass on views that have a Z offset.

.glassBackgroundEffect(displayMode: .implicit)

There are two conditions that will trigger a view to show glassBackgroundEffect when using implicit display mode.

  1. When there are no ancestor views rendering glassBackgroundEffect
  2. When the view is offset on the Z axis

This layout has three card views that display in an HStack. When the background is toggled on, they don’t render their own glass. We can show glass on these cards by hiding the background or by offsetting each view along the z-axis.

A video demo showing child views adopting glass panes when offset from a parent view

Lab Code

struct Lab082: View {

    @State private var showBackground = true
    @State private var showDepth = false

    var body: some View {
        VStack(alignment: .center) {
            Spacer()
            HStack {
                CardView(imageName: "applewatch.watchface", title: "Apple Watch", caption: "Series 11")
                    .offset(z: showDepth ? 40 : 0)

                CardView(imageName: "iphone.gen3", title: "iPhone", caption: "Pro 17, Silver")
                    .offset(z: showDepth ? 120 : 0)

                CardView(imageName: "airpods.pro", title: "AirPods Pro", caption: "3rd Generation")
                    .offset(z: showDepth ? 80 : 0)
            }
            Spacer()
        }
        .padding(60)

        .glassBackgroundEffect(displayMode: showBackground ? .always : .never)
        .ornament(attachmentAnchor: .scene(.bottom), ornament: {
            HStack{
                Toggle(isOn: $showBackground.animation()) {
                    Text("Background")
                }
                .toggleStyle(.button)
                Toggle(isOn: $showDepth.animation()) {
                    Text("Depth")
                }
                .toggleStyle(.button)
            }
            .controlSize(.small)
            .padding(4)
            .glassBackgroundEffect()
        })
    }
}

fileprivate struct CardView : View {

    @State var imageName: String
    @State var title: String
    @State var caption: String

    var body: some View {
        VStack {
            Image(systemName: imageName)
                .font(.largeTitle)
            Text(title)
                .font(.title)
            Text(caption)
                .font(.caption)

        }
        .padding(12)
        .frame(width: 180, height: 120,)
        .glassBackgroundEffect(displayMode: .implicit)
    }
}

Support our work so we can continue to bring you new examples and articles.

Questions or feedback?