Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Use Xcode Previews with SwiftUI
Written by Team Kodeco

One of the great features of SwiftUI is how it integrates with Xcode previews, which allows you to see your user interface code live as you work on it. Previews provide a fast and efficient way to develop and iterate on your app’s UI design.

You can manipulate the preview by using the controls in the canvas window or by editing the code directly in the Xcode editor. As you make changes to the code, the preview updates in real-time, allowing you to see how these changes affect the appearance of the UI.

Here’s an example of how to use previews with SwiftUI:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Hello, SwiftUI!")
        .padding()
      Button(action: {
        print("Button tapped!")
      }) {
        Text("Tap me!")
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .previewDevice("iPhone 14 Pro")
  }
}

In this example, we have a simple VStack that contains a Text view and a Button view. The ContentView_Previews struct is responsible for generating the live preview.

When you run this in Xcode and display the preview, you’ll see your UI displayed as it looks on an iPhone 14 Pro. You can then manipulate this view in real-time, either by modifying the code or using the tools in the preview window.

Previewing a SwiftUI view.
Previewing a SwiftUI view.

In addition to previewing the UI on different devices, you can also set different preview configurations for things like light versus dark appearance, orientation, accessibility settings and more. For example, you can replace ContentView_Previews with the following:

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .previewDevice("iPhone 14 Pro")
    ContentView()
      .preferredColorScheme(.dark)
    ContentView()
      .previewInterfaceOrientation(.landscapeLeft)
  }
}

You should now see a selection of 3 different previews in your canvas: one for an iPhone 14 Pro, one for Dark Mode and one for landscape orientation:

Multiple SwiftUI previews.
Multiple SwiftUI previews.

Using previews is a powerful tool for developing user interfaces with SwiftUI. With a little bit of practice, you’ll be able to quickly and easily iterate on your designs and create beautiful and responsive apps.

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.