6

Update Xcode 13 The code sample below works as expected in Xcode 13.

Update from Apple Frameworks Engineer October 2020:

Unfortunately there is no current workarounds to let you preview this outside of the live preview.


Is it possible to create a SwiftUI preview of a presented sheet without running the Live Preview? For example:

struct Sheet_Previews: PreviewProvider {
    static var previews: some View {
        Text("Background").sheet(isPresented: .constant(true)) {
            Text("Sheet")
        }
    }
}

The above results in the following preview:

enter image description here

In order for the sheet content to be presented in the preview, you must run the Live Preview:

enter image description here

Clay Ellis
  • 4,960
  • 2
  • 37
  • 45

2 Answers2

7

Xcode 13.0 seems to handle this correctly without starting a Live Preview.

So this is working now:

struct Sheet_Previews: PreviewProvider {
    static var previews: some View {
        Text("Background").sheet(isPresented: .constant(true)) {
            Text("Sheet")
        }
    }
}
Florian Mielke
  • 3,310
  • 27
  • 31
1

Just let preview provide to show both views, for parent and sheet, like

struct Sheet_Previews: PreviewProvider {
    static var previews: some View {
        Group {       // << will create two previews
            Text("Background")  // << parent view here
            Text("Sheet")       // << sheet view here
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • That would create two separate previews — I'm looking for the sheet content to be presented in the sheet so that I can preview what the content would look like as a sheet, not just as a view on its own. Much like you would wrap your preview in a `NavigationView` in order to preview what it would look like in that context. (I don't really care what the view is behind the presented sheet, but it has to be something in order to run, hence just a simple `Text`.) – Clay Ellis Sep 28 '20 at 05:55
  • I understand but preview provider does not give such feature now (and I'm not sure if it will) and it is not the same as NavigationView - NavigationView constructs same view hierarchy, but sheet introduces dynamically different view hierarchy (with own host view), so it looks like out of scope for preview provider. – Asperi Sep 28 '20 at 06:11