Mastering Xcode Previews

Description: Xcode 11 displays previews of your user interface right in the editor, streamlining the edit-debug-run cycle into a seamless workflow. Learn how previews work, how to optimize the structure of your SwiftUI app for previews, and how to add preview support to your existing views and view controllers.

  • The preview API is part of SwiftUI, but we can use it for preview UIKit views as well.
  • To create previews on the current file, create a new Struct conforming to the PreviewProvider protocol: usually this preview will returns the view of the current file and that’s it.
  • Wrap the preview declarations with #if DEBUG #endif compile conditions to make sure previews will be compiled only in debug mode.
  • Instead of a device, we can also focus on the raw view itself (a-la xib files), and that is done via the .previewLayout() API.
  • Use Group { .. } to display multiple previews at once.
  • Override environment variables with the .environment(\.sizeCategory, .extraLarge) API
#if DEBUG

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      ForEach(ContentSizeCategory.allCases, id: \.hashValue) { size in
        ContentView()
          .environment(\.sizeCategory, size)
      }
    }
  }
}

#endif

Development assets

  • New in Xcode 11
  • Used (for example) when we want to preview images without having needing to relay on a network or with the need to add assets in our final binary.

UIKit previews

  • Works exactly like SwiftUI previews
  • Create a PreviewProvider.
  • Create a UIViewRepresentable/UIViewControllerRepresentable.
  • Add UIViews/UIViewControllers in the PreviewProvider's previews static property.

Canvas Protips:

  • Use the pin button in the bottom left corner of the preview to pin the current preview and jump to other files.
  • Show/hide the canvas by pressing + + .

MVVM

Apple is really pushing us to use the MVVM architecture with SwiftUI: Model-view-viewmodel.

Apple even suggests to add tests on how data migrates from a model to a view model:

Missing anything? Corrections? Contributions are welcome 😃

Related

Written by

Federico Zanetello

Federico Zanetello

Software engineer with a strong passion for well-written code, thought-out composable architectures, automation, tests, and more.