Skip to content

Instantly share code, notes, and snippets.

@sowenjub
Last active May 16, 2021 21:00
Show Gist options
  • Save sowenjub/c6aabd15da5acdfdee49e0f371705837 to your computer and use it in GitHub Desktop.
Save sowenjub/c6aabd15da5acdfdee49e0f371705837 to your computer and use it in GitHub Desktop.
A generic struct to show previews in various states. A combination of https://www.avanderlee.com/swiftui/previews-different-states/ and https://www.swiftjectivec.com/xcode-preview-snips/
struct UIElementPreview<Value: View>: View {
enum Format {
case device, sizeThatFits, darkMode, rightToLeft, localizations, contentSizes, contentSizesMinMax
}
var formats: [Format]
/// Filter out "base" to prevent a duplicate preview.
private let localizations = Bundle.main.localizations.map(Locale.init).filter { $0.identifier != "base" }
private let viewToPreview: Value
init(_ viewToPreview: Value, formats: [Format] = [.device, .sizeThatFits, .darkMode, .rightToLeft, .contentSizes, .contentSizesMinMax]) {
self.formats = formats
self.viewToPreview = viewToPreview
}
var body: some View {
Group {
if formats.contains(.device) {
self.viewToPreview
.previewLayout(.device)
.padding()
.previewDisplayName("Default")
}
if formats.contains(.sizeThatFits) {
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Default")
}
if formats.contains(.darkMode) {
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewDisplayName("Dark Mode")
}
if formats.contains(.rightToLeft) {
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.environment(\.layoutDirection, .rightToLeft)
.previewDisplayName("Right to Left")
}
if formats.contains(.localizations) {
ForEach(localizations, id: \.identifier) { locale in
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.environment(\.locale, locale)
.previewDisplayName(Locale.current.localizedString(forIdentifier: locale.identifier))
}
}
if formats.contains(.contentSizes) {
ForEach(ContentSizeCategory.allCases, id: \.self) { contentSize in
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.environment(\.sizeCategory, contentSize)
.previewDisplayName("\(contentSize)")
}
}
if formats.contains(.contentSizesMinMax) {
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.environment(\.sizeCategory, ContentSizeCategory.allCases.first!)
.previewDisplayName("\(ContentSizeCategory.allCases.first!)")
self.viewToPreview
.previewLayout(.sizeThatFits)
.padding()
.environment(\.sizeCategory, ContentSizeCategory.allCases.last!)
.previewDisplayName("\(ContentSizeCategory.allCases.last!)")
}
}
}
}
struct UIElementPreview_Previews: PreviewProvider {
static var previews: some View {
UIElementPreview(Text("Hello, world!"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment