Spatial SwiftUI: offset modifier

Using z axis offset to lift our views out of their window.

Using offset is very simple. We specify an axis and provide a value.

.offset(z: 12)

Gotcha: offset(z:) and offset(x:y:) are different modifiers! The XY variant has been around for years. My guess is that the visionOS team needed to add this and didn’t want to break any existing code. We can still use all three axis types, but we have to use more than one modifier.

.offset(x: 12, y: 12)
.offset(z: 12)

This demo will animate the offset values when we tap the toggle button.

struct Example030: View {

    @State var showOffset = false

    var body: some View {
        VStack(spacing: 24) {

            Toggle("Toggle Offset", isOn: $showOffset.animation())
                .toggleStyle(.button)

            HStack(spacing: 24) {

                RoundedRectangle(cornerRadius: 12.0)
                    .foregroundStyle(.stepRed)
                     // offset(z:) and offset(x:y:) are different modifiers!
                    .offset(z: showOffset ? 12 : 0)
                    .offset(x: showOffset ? 48 : 0)
                    
                RoundedRectangle(cornerRadius: 12.0)
                    .foregroundStyle(.stepBlue)
                    .offset(z: showOffset ? 24 : 0)
                    
                RoundedRectangle(cornerRadius: 12.0)
                    .foregroundStyle(.stepGreen)
                    .offset(z: showOffset ? 36 : 0)
                    .offset(x: showOffset ? -48 : 0)

            }
            .padding(12)
        }
        .padding(12)
    }
}

Watch the video demo:

Download the Xcode project with this and many more examples from Step Into Vision.

Some examples are provided as standalone Xcode projects. You can find those here.

Questions or feedback?