In SwiftUI, how do you declare previews with the #Preview macro, and how do names and traits let one view show several states?
answer
- a macro at file scope
- one declaration per state
- unnamed means labelled by line number
- traits for layout and orientation
basics
~20 s#Preview is a freestanding macro that takes an optional name, optional traits and a closure returning the view to render. Write one named #Preview per state, and use traits such as sizeThatFitsLayout or landscapeLeft for layout and orientation.
solid answer
~40 s`#Preview { FeedView(posts: Post.samples) }` is all a preview needs: the closure builds the view with whatever inputs and models it needs, and Xcode renders it beside the code. Each `#Preview` in a file is a separate preview. Without a name the canvas labels it by line number, so `#Preview("Empty feed")` and `#Preview("Long post")` make each state easy to find. The `traits:` form (iOS 17) adds `PreviewTrait` values such as `.sizeThatFitsLayout`, `.fixedLayout(width:height:)` or `.landscapeLeft`, and traits that don't apply to the platform are ignored. Dark mode and right-to-left are environment modifiers in the body, not traits. In the iOS 27 SDK, `PreviewProvider`, `previewDisplayName` and `previewLayout` are deprecated in favour of the macro.
code
swift · 34 linesimport SwiftUI
struct Post: Identifiable {
let id: Int
let text: String
static let samples = [Post(id: 1, text: "First light over the bay.")]
static let veryLong = Post(id: 2, text: String(repeating: "A very long post. ", count: 40))
}
struct FeedView: View {
let posts: [Post]
var body: some View {
if posts.isEmpty {
ContentUnavailableView("No posts yet", systemImage: "text.bubble")
} else {
List(posts) { Text($0.text) }
}
}
}
#Preview("Empty feed") {
FeedView(posts: [])
}
#Preview("Long post", traits: .sizeThatFitsLayout) {
Text(Post.veryLong.text).padding()
}
#Preview("Dark, right-to-left", traits: .landscapeLeft) {
FeedView(posts: Post.samples)
.preferredColorScheme(.dark)
.environment(\.layoutDirection, .rightToLeft)
.environment(\.locale, Locale(identifier: "ar"))
}go deeper
Recall the basic shape: a #Preview below the view, a name per state, and a trait such as sizeThatFitsLayout for a small component.
Explain which variations are traits and which are environment modifiers, and why named previews beat line-number labels once a file has several.
Show a preview set that covers the states that break in production, such as empty, very long, dark and right-to-left, and migrate old PreviewProvider code without losing names or layouts.
Treat previews as the team's visual fixtures: agree which states every screen must preview, and plan the move off the PreviewProvider APIs the iOS 27 SDK deprecates.
## What a preview declaration is A **preview** in SwiftUI is a `#Preview` declaration: a freestanding macro that you write at file scope, usually right below the view it shows. Its closure is a content builder that returns the view to render, together with whatever that view needs to run normally: inputs, sample models, modifiers and enclosing containers. Xcode builds the closure and draws the result beside your code, refreshing it as you edit. ```swift #Preview { FeedView(posts: Post.samples) } ``` The simplest form, `#Preview(_:body:)`, takes an optional name and the closure. Its availability line reaches back to iOS 13, so even a target with an old deployment target can use it. The form that also takes traits, `#Preview(_:traits:_:body:)`, needs iOS 17. ## Several previews per view, and why names matter A file can hold as many `#Preview` declarations as you like. Each one becomes a separate preview, and the canvas lets you pick between them. Without a name, the canvas labels each preview with **the line number** where it appears in source. That label stops meaning anything once a file has five of them, so name them after the state they show: - `#Preview("Empty feed")`: no posts, so the empty state is visible. - `#Preview("Long post")`: one post whose text wraps across many lines. - `#Preview("Dark, right-to-left")`: the same feed in a dark appearance with Arabic layout direction. Treat each named preview as a fixture for one state you care about. A social feed screen typically wants the empty, normal, very long and error states, plus at least one dark and one right-to-left run. ## Traits change how the preview is laid out Traits are `PreviewTrait` values passed through `traits:` (one required trait, then any number of additional ones). In the iOS 27 SDK the view traits are: | Trait | What it does | Available from | |---|---|---| | `.defaultLayout` | the standard device-sized layout | iOS 17 | | `.sizeThatFitsLayout` | sizes the preview to the view itself, handy for a row or a button | iOS 17 | | `.fixedLayout(width:height:)` | renders inside a container of a fixed size | iOS 17 | | `.portrait`, `.portraitUpsideDown`, `.landscapeLeft`, `.landscapeRight` | device orientation | iOS 17 | | `.modifier(_:)` | applies a `PreviewModifier` | iOS 18 | | `.assistiveAccess` | shows the view as it appears in Assistive Access | iOS 26 | Apple's documentation notes that the macro **ignores traits that do not apply** to the current context; the `portrait` trait has no effect on a visionOS preview, for example. ## Variations that are not traits Dark mode, layout direction, locale and Dynamic Type are not preview traits. They are **environment values**, so you set them with ordinary modifiers inside the preview body: 1. `.preferredColorScheme(.dark)` or `.environment(\.colorScheme, .dark)` for a dark appearance. 2. `.environment(\.layoutDirection, .rightToLeft)` together with `.environment(\.locale, Locale(identifier: "ar"))` for a right-to-left language. 3. `.dynamicTypeSize(.accessibility3)` for a large text size. How strings are localized and how VoiceOver reads the screen belong to the lessons on localization and accessibility. The preview only needs to put the view into each state. ## One preview per argument The iOS 26 SDK added `#Preview(_:traits:arguments:body:)`. It takes an array and a closure that maps each element to a view, and it creates a group of previews, one per argument. That is a compact way to cover a list of states, such as an array of sample posts, without copying the declaration. Its availability line reads iOS 26 (macOS 27), so an app that still deploys to iOS 17 or 18 keeps writing one named `#Preview` per state. ## From PreviewProvider to #Preview Before the macro arrived in the June 2023 release, previews were types that conformed to `PreviewProvider` and returned a static `previews` property, with modifiers such as `previewDisplayName(_:)`, `previewLayout(_:)` and `previewInterfaceOrientation(_:)` for the name, layout and orientation. In the iOS 27 SDK all of these are **deprecated**, and each deprecation names its replacement: - `PreviewProvider`: "Use #Preview instead." - `previewDisplayName(_:)`: use the macro's name argument. - `previewLayout(_:)`: use `.sizeThatFitsLayout` or `.fixedLayout(width:height:)` traits. - `previewInterfaceOrientation(_:)`: use `.landscapeLeft` or another orientation trait. - `previewDevice(_:)`: use the device picker in Xcode's canvas. Deprecated means old previews still compile with a warning. New code should use the macro, and migrating is mostly mechanical: one `#Preview` per former `previews` branch, with the name and traits moved into the macro's arguments. ## Key points - One view, several named previews, one per state you need to see. - Traits cover layout, orientation, Assistive Access and preview modifiers. The environment covers appearance, direction, locale and text size. - In the iOS 27 SDK, `PreviewProvider` and its modifiers are deprecated in favour of `#Preview`.
- How can you cover a list of states without writing one #Preview per state?The iOS 26 SDK added `#Preview(_:traits:arguments:body:)`: pass an array and a closure that maps each element to a view, and the canvas shows a group of previews, one per argument. Its availability line reads iOS 26, so a target that still deploys to iOS 17 or 18 writes one named `#Preview` per state instead.
- Why is dark mode set with a modifier in the body rather than passed as a trait?In the iOS 27 SDK, preview traits cover layout, orientation, Assistive Access and preview modifiers. Color scheme, layout direction, locale and Dynamic Type are environment values, so the preview sets them with `preferredColorScheme(_:)`, `environment(_:_:)` or `dynamicTypeSize(_:)` on the view it returns, or bundles them in a shared `PreviewModifier`.
- A source file can hold only one #Preview, so each variant needs its own file.
- An unnamed preview is labelled with the view type's name in the canvas.
- Dark mode and right-to-left are preview traits passed through traits:.
- PreviewProvider is still the recommended way to declare previews in the iOS 27 SDK.
- The portrait trait forces portrait on every platform, including visionOS.
Assumes the iOS 27 SDK, which deprecates PreviewProvider and its preview modifiers in favour of #Preview; the traits form needs iOS 17 and the arguments form iOS 26.