Created
May 3, 2020 18:09
-
-
Save doroshenko/12f9e04cb62920643ddc4f48471b2a1f to your computer and use it in GitHub Desktop.
Unified preview style for SwiftUI's PreviewProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
var body: some View { | |
Text("Hello, World!") | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
.previewStyle(.compact) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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