Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Customizing SwiftUI Previews
Written by Team Kodeco

SwiftUI previews are a powerful tool for UI design, offering an instant glance at your interface without having to build and run your entire application. This cookbook entry will guide you on customizing SwiftUI previews to tailor them to your needs.

Consider a simple view:

struct ContentView: View {
  var body: some View {
    Text("Hello, world!")
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .background()
  }
}

The corresponding preview can be customized like this:

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .previewLayout(.fixed(width: 300, height: 70))
      .previewDisplayName("Custom Preview")
      .environment(\.colorScheme, .dark)
  }
}

Here’s what your preview should look like:

A customized SwiftUI preview.
A customized SwiftUI preview.

In this example, ContentView_Previews uses several modifiers on ContentView() to customize the preview:

  • .previewLayout(.fixed(width: 300, height: 70)) sets the preview’s dimensions.
  • .previewDisplayName("Custom Preview") names the preview for easy identification, which is handy as you add additional previews.
  • .environment(\.colorScheme, .dark) applies a dark color scheme to the preview.

These modifiers help adjust the preview to match your expectations and reflect the application’s intended look and behavior.

For further customization, you can also preview your interface on specific device types or provide an environment object. For example, try updating the preview to the following:

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .previewDevice(PreviewDevice(rawValue: "iPhone SE"))
  }
}

Your preview should look like:

A SwiftUI preview on a custom device.
A SwiftUI preview on a custom device.

SwiftUI previews serve as a test drive for your application’s UI, ensuring the final product runs smoothly. By effectively using customization options, you can maximize the potential of SwiftUI previews to create beautiful and functional interfaces.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.