Skip to content

Preview Group

Paul Zabelin edited this page Jun 6, 2022 · 3 revisions

Some views might use several previews for different variations:

for example to preview view on different backgrounds:

import PreviewGroup

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        PreviewGroup {
            ContentView()
                .background(Color.yellow)
            ContentView()
                .background(Color.green)
        }
    }
}

by using PreviewGroup instead of standard SwiftUI.Group we get snapshots for each element in the group:

verifySnapshot(ContentView_Previews.self)

will produce 2 files from the above preview:

  • ContentView.1.png with yellow background
  • ContentView.2.png with green background
Snapshot Image
ContentView.1.png Hello world on yellow
ContentView.2.png Hello world on green

Installation

Since PreviewGroup needs to be part of main app target, it can be install by linking with SnapshotTestingPreviewGroup library from Swift package.

Another Example

Popularity Badge View shows percentage score by closing ring in different colors:

struct PopularityBadge_Previews : PreviewProvider {
    static var previews: some View {
        PreviewGroup {
            PopularityBadge(score: 80)
            PopularityBadge(score: 10)
            PopularityBadge(score: 30)
            PopularityBadge(score: 50)
        }
    }
}

will generate 4 snapshots:

Snapshot Image
PopularityBadge.1.png 80%
PopularityBadge.2.png 10%
PopularityBadge.3.png 30%
PopularityBadge.4.png 50%
Clone this wiki locally