How it works
PreviewContext is a protocol that exposes the contextual values surrounding a preview — the environment in which Xcode renders a #Preview snapshot, such as the simulated device or layout. SwiftUI reads these values through a typed key lookup, much like the environment, so a preview can be configured and inspected without changing the view itself. Reach for PreviewContext when you need to query or supply per-preview configuration that lives outside the view's own state, letting the same view render under different contexts.
Adopt the PreviewContext protocol
PreviewContext is the protocol a context type conforms to in order to vend values to a preview. Any view you place in a preview — such as
PreviewContextDemohere — is rendered inside one of these contexts, and conforming a type to PreviewContext is what lets it participate in that lookup.Read values with the subscript
PreviewContext requires a key-based subscript,
subscript(key:), that returns the value for a givenPreviewContextKey. This is the single access point the framework uses to pull contextual data while it assembles a preview of a view like theVStackreturned frombody.Define values through PreviewContextKey
Each contextual value is identified by a type conforming to
PreviewContextKey, which supplies adefaultValue. Keys are how you name a piece of preview configuration — device, layout, or your own custom setting — so the subscript on PreviewContext can resolve it the same way the demo'sText("Supplies values like device & layout to a #Preview")describes.Connect a context to a preview
Because PreviewContext sits beside the preview machinery rather than the runtime view hierarchy, it shapes how the snapshot is produced, not what
PreviewContextDemodraws. TheImage,Text, and modifiers inbodystay context-agnostic, while the surrounding PreviewContext determines the device and layout the preview is rendered under.
PreviewContextDemo() you render in a #Preview and pass a different layout (for example a fixed size) so you can watch the same VStack redraw under a changed PreviewContext.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct PreviewContextDemo: View {
var body: some View {
VStack(spacing: 8) {
Image(systemName: "rectangle.portrait.on.rectangle.portrait")
.font(.largeTitle)
.foregroundStyle(.tint)
Text("Preview Context")
.font(.headline)
Text("Supplies values like device & layout to a #Preview")
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.padding()
}
}