Why previews feel unreliable
Previews are the fastest feedback loop in iOS development when they work, and a source of “Cannot preview in this file” banners when they don’t. Most teams end up in one of two places: previews that only show the happy path with hard-coded data, or previews nobody opens because they broke months ago. Both come from the same gap. A preview is a small program that builds your module and runs your view, so it needs the same care as the view itself: inputs it can construct, dependencies it can satisfy, and code that doesn’t assume it’s running inside the full app.
The #Preview macro
#Preview replaced the PreviewProvider protocol in Xcode 15, and the Xcode 27 release notes now list PreviewProvider and its family of modifiers as deprecated. Apple’s documentation lists Preview(_:body:) as available from iOS 13, so it works for older deployment targets too. Antoine van der Lee’s early write-up ran into an availability error with iOS 16 targets in the Xcode 15 betas. With current Xcode the documented availability covers those projects.
The macro also works with UIKit and AppKit. Return a UIView or UIViewController from the closure and the canvas shows it, which makes previews useful in projects that are still mostly UIKit.
#Preview("Empty inbox") {
InboxView(messages: [])
}
#Preview("Full inbox") {
InboxView(messages: Message.samples)
}
#Preview("Settings screen") {
let controller = SettingsViewController()
controller.title = "Settings"
return controller
}
The views and view controllers in these snippets stand in for your own types. Name every preview. The name labels its tab in the canvas, and without one Xcode falls back to the line number, which changes as you edit. Each file can hold as many previews as you need. Since Xcode 27, each #Preview and #Playground tab can be pinned in the canvas on its own, so you can keep one screen visible while editing a component in another file.
Traits: layout, orientation and shared setup
Pass PreviewTrait values (iOS 17+) after the name:
.sizeThatFitsLayoutshrinks the container to the view, which suits components such as cells, buttons and badges..fixedLayout(width:height:)previews at an exact size..portrait,.landscapeLeft,.landscapeRightand.portraitUpsideDownset orientation..assistiveAccessapplies the Assistive Access style on iOS and iPadOS..modifier(_:)attaches aPreviewModifierfor shared setup, covered below.
#Preview("Row states", traits: .sizeThatFitsLayout) {
VStack(spacing: 12) {
MessageRow(message: .samples[0])
MessageRow(message: .unreadSample)
MessageRow(message: .longSubjectSample)
}
.padding()
}
For environment conditions there’s no special trait. Apply ordinary modifiers inside the preview, as Majid Jabrayilov shows in The power of previews in Xcode:
#Preview("Dark, large text") {
InboxView(messages: Message.samples)
.preferredColorScheme(.dark)
.dynamicTypeSize(.accessibility3)
}
The canvas also has its own variant controls, so you don’t have to code every combination. Xcode 27 adds overrides for localization, Color Scheme Contrast (standard or increased contrast) and Control Borders, plus a Resizable Canvas mode for iOS that lets you drag the preview container to any size. That last one is the quickest way to check how a layout behaves between iPhone and iPad widths.
@Previewable: state without wrapper views
A view that takes a Binding used to need a throwaway wrapper view in the preview to own the @State. The Previewable() macro, introduced with Xcode 16 and available from iOS 17, removes that. Tag a dynamic property at the root of the preview body, and the macro generates the wrapper for you. Van der Lee’s @Previewable article shows the generated wrapper view if you expand the macro.
#Preview("Toggle filter") {
@Previewable @State var showsUnreadOnly = false
FilterBar(showsUnreadOnly: $showsUnreadOnly)
}
It works with any DynamicProperty, not only @State. Jabrayilov points out it’s handy with @Query and @Environment, which lets a preview read from a model container you set up elsewhere. Two limits from Apple’s docs: you can only use it inside a #Preview body, and it’s SwiftUI only, so UIKit and AppKit previews can’t use it.
#Preview(arguments:): one preview per input
Xcode 27 adds #Preview(arguments:), which takes an array and renders one preview per element in a grid. Clicking one opens it in interactive mode. Apple’s reference lists the macro as available from iOS 26.
enum DeliveryState: CaseIterable {
case pending, sent, failed
}
#Preview("Delivery states", traits: .sizeThatFitsLayout, arguments: DeliveryState.allCases) { state in
DeliveryBadge(state: state)
}
This replaces a hand-written VStack or a ForEach over states. Because the macro has an iOS 26 availability, a project with an older deployment target may get an availability error. Keep separate named previews there.
Sample data that doesn’t leak into the app
Pass views only what they need
Apple’s previews article gives the advice that makes everything else easier: build views from the minimal data they display, favouring simple value types, and avoid passing in objects that fetch data. A MessageRow(message: Message) is trivial to preview. A MessageRow(id: UUID, store: MessageStore) needs a working store. If a view is hard to preview, that’s usually a design signal.
Put sample values next to the type they describe:
extension Message {
static let samples: [Message] = [
Message(subject: "Lunch on Friday?", sender: "Ana", isUnread: true),
Message(subject: "Invoice 2026-114", sender: "Billing", isUnread: false)
]
}
Message stands in for your own model. Include the awkward cases deliberately: a very long subject, an empty string, a name in a right-to-left language. Those are the samples that catch layout bugs.
For images, JSON fixtures and other files you only need in previews, use Development Assets. In the target’s General tab, add them under Development Assets, and Xcode makes them available to previews without shipping them in the app.
PreviewModifier for expensive setup
Some views need a real environment, such as a SwiftData container or an @Observable app model. Recreating it in every preview is slow. A PreviewModifier (iOS 18+) builds a shared context once in makeSharedContext(), the preview system caches it, and body(content:context:) applies it to each preview that uses the modifier.
import SwiftData
import SwiftUI
struct SampleMessages: PreviewModifier {
static func makeSharedContext() async throws -> ModelContainer {
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: StoredMessage.self, configurations: configuration)
for message in StoredMessage.samples {
container.mainContext.insert(message)
}
return container
}
func body(content: Content, context: ModelContainer) -> some View {
content.modelContainer(context)
}
}
#Preview("Inbox with data", traits: .modifier(SampleMessages())) {
@Previewable @Query var messages: [StoredMessage]
StoredInboxView(messages: messages)
}
StoredMessage is a SwiftData @Model with a samples array, left out here. The in-memory configuration keeps previews from writing to disk or touching the app’s real store.
Why previews break, and how to fix them
The target doesn’t build
A preview builds the whole module that contains the file. A compile error in an unrelated file stops every preview in that target. Fix the build first, and check the issue navigator rather than the canvas banner, which often shows only the first error. A view in a small Swift package can be previewed with that package’s scheme selected, which builds far less than the whole app.
App code runs when it shouldn’t
The preview process runs your module’s code, including your App type’s initializer, singletons and static properties that touch the network, the keychain, CloudKit or a database. Some of those crash or hang outside a real app launch.
The durable fix is dependency injection: views take protocols or plain values, and only the real app wires up live services. As an escape hatch, an Apple engineer in the Xcode 16 previews thread recommends checking the XCODE_RUNNING_FOR_PREVIEWS environment variable at runtime:
import Foundation
enum RuntimeContext {
static var isPreview: Bool {
ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}
}
Teams split on this. Some scatter isPreview checks through their code, others treat any such check as a design smell. This article recommends the second view for views and models, and accepts the check in one place: the composition root where you decide which services to create.
Missing environment values
A view that reads @Environment(AppModel.self) crashes in a preview that doesn’t provide one. The canvas shows a crash with little explanation. Provide the value in the preview with .environment(...), or inside a PreviewModifier if several previews need it. The same applies to .modelContainer for views using @Query.
Main actor warnings
Before Xcode 27, calling main-actor APIs from a #Preview body could produce concurrency warnings or runtime check failures in Swift 6 mode. The Xcode 27 release notes say code inside #Preview now explicitly runs on the main actor, so these go away after upgrading.
Build scripts that modify files
Since Xcode 16, previews share build products with Debug builds, which made them much faster. The forum thread above also explains the cost: ENABLE_PREVIEWS no longer reliably identifies a preview build, and Apple’s build engineers say preview builds can’t be told apart from regular builds at build time. A Run Script phase that formats or rewrites source files then makes previews rebuild in a loop. Run auto-fixing formatters and linters from a git hook, and keep build phases read-only. Xcode 27 also fixed previews restarting their build repeatedly in large workspaces when files were written into derived data.
When nothing else works
- Use Legacy Previews Execution. Editor > Canvas > Use Legacy Previews Execution switches to the old separate build. Apple’s forum reply calls it a short-term escape hatch, and it’s per project and per Xcode version.
- Read the diagnostics. The canvas error banner offers diagnostics with the full build and crash details. Xcode 27 shows complete diagnostic information for crashed previews more often and clearer errors for timeouts and dependency cycles.
- Check the destination. Xcode 27 shows a placeholder instead of an error when the selected destination has no installed simulator runtime. Install the runtime or pick another device.
- Clean as a last resort. Clearing DerivedData fixes stale state after an Xcode update. It also costs you a full rebuild, so don’t make it a habit.
Checklist
| Goal | Use |
|---|---|
| Several states of one view | Named #Preview blocks, or #Preview(arguments:) on iOS 26+ targets |
| Small component | .sizeThatFitsLayout |
| Binding-driven view | @Previewable @State |
| SwiftData or shared app model | PreviewModifier with an in-memory container |
| Dark mode, large text | .preferredColorScheme, .dynamicTypeSize, or canvas variants |
| Preview-only images and fixtures | Development Assets |
| Preview crashes on launch | Inject services, provide environment values |
| Preview rebuilds in a loop | Keep build scripts from modifying files |
| Preview broken after an upgrade | Read diagnostics, then try Legacy Previews Execution |
Sources and further reading
- Adding previews to your interface files Apple Developer Documentation
- Previews in Xcode Apple Developer Documentation
- Previewable() Apple Developer Documentation
- PreviewModifier Apple Developer Documentation
- PreviewTrait Apple Developer Documentation
- Preview(_:traits:arguments:body:) Apple Developer Documentation
- Xcode 27 Release Notes Apple Developer Documentation
- Xcode 16 no longer sets ENABLE_PREVIEWS=YES for preview builds Apple Developer Forums
- The power of previews in Xcode Majid Jabrayilov, Swift with Majid
- @Previewable: Dynamic SwiftUI Previews Made Easy Antoine van der Lee, SwiftLee
- #Preview SwiftUI Views using Macros Antoine van der Lee, SwiftLee