Skip to content

Instantly share code, notes, and snippets.

@doroshenko
Created May 3, 2020 18:09
Show Gist options
  • Save doroshenko/12f9e04cb62920643ddc4f48471b2a1f to your computer and use it in GitHub Desktop.
Save doroshenko/12f9e04cb62920643ddc4f48471b2a1f to your computer and use it in GitHub Desktop.
Unified preview style for SwiftUI's PreviewProvider
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewStyle(.compact)
}
}
import SwiftUI
enum PreviewStyle {
case compact
case full
}
extension View {
func previewStyle(_ style: PreviewStyle) -> some View {
Group {
if style == .compact {
compactView()
} else if style == .full {
fullView()
}
}
}
private func compactView() -> some View {
modifier(PreviewStyleCompact())
}
private func fullView() -> some View {
modifier(PreviewStyleFull())
}
}
struct PreviewStyleCompact: ViewModifier {
func body(content: Content) -> some View {
ForEach([ColorScheme.light, .dark], id: \.self) { scheme in
content
.background(Color(.systemBackground))
.environment(\.colorScheme, scheme)
.previewLayout(.sizeThatFits)
}
}
}
struct PreviewStyleFull: ViewModifier {
func body(content: Content) -> some View {
ForEach([ColorScheme.light, .dark], id: \.self) { scheme in
content
.background(Color(.systemBackground))
.environment(\.colorScheme, scheme)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment