Contents

PreviewModifier

A type that defines an environment in which previews can appear.

Declaration

@MainActor protocol PreviewModifier

Overview

Conforming types can define shared contexts that will be cached by the preview system, then reused across participating previews. For example, you might create a model container here and populate it with sample data; in your body method you would then apply it to the preview using the .modelContainer view modifier.

struct SampleData: PreviewModifier {
    static func makeSharedContext() throws -> ModelContainer {
        let container = try ModelContainer(for: Snack.self)
        container.mainContext.insert(Snack.potatoChips)
        return container
    }

    func body(content: Content, context: ModelContainer) -> some View {
        content.modelContainer(context)
    }
 }

Use the .modifier preview trait to attach modifiers to a preview.

#Preview(traits: .modifier(SampleData())) {
    @Previewable @Query var snacks: [Snack]
    return SnackView(snack: snacks.first!)
}

Topics

Associated Types

Instance Methods

Type Aliases

Type Methods

See Also

Defining a preview