How it works
A type that produces view previews in the Xcode canvas. Conform to PreviewProvider to give Xcode a self-contained sample of a view it can render and refresh continuously while you edit, without building and launching your full app. Reach for it whenever you want a fast design loop on a single view in isolation, supplying exactly the data and configuration that view needs to draw. The protocol is purely a development-time hook: the previews it produces never ship in your running application.
Conform a type to PreviewProvider
Declare a separate type alongside the view under design and adopt the protocol on it. Xcode discovers any type that conforms to
PreviewProviderin a file and drives it to populate the canvas, so the conforming type acts as the entry point for previewing a view such asPreviewProviderDemo.Return content from the previews property
The protocol's single requirement is a static
previewsproperty whose type is an associatedPreviewsview. Whatever you return there is what the canvas renders, so you instantiate the target view inside it — herePreviewProviderDemo()— supplying any initializer arguments or sample state the view requires to display.Treat previews as ordinary SwiftUI content
Because
previewsreturns aView, you compose it with the same building blocks as the live UI. The returned view carries its own layout and modifiers — theVStack,Image, andTextwith.padding()inPreviewProviderDemo— so what you see in the canvas matches what the type renders at runtime.Configure each preview with view modifiers
Apply standard SwiftUI modifiers to the returned content to pin down how a single preview appears — for example sizing the canvas, naming the preview, or selecting a color scheme — letting you exercise one specific configuration of
PreviewProviderDemowithout touching the view's own definition.
PreviewProviderDemo() to the returned previews content and attach .preferredColorScheme(.dark) to it to see the same view rendered light and dark side by side in the canvas.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 PreviewProviderDemo: View {
var body: some View {
VStack(spacing: 12) {
Image(systemName: "eye")
.font(.largeTitle)
.foregroundStyle(.blue)
Text("Preview")
.font(.title2.bold())
Text("A PreviewProvider renders this view in the Xcode canvas.")
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.padding()
}
}