Skip to content

Instantly share code, notes, and snippets.

@colejd
Last active January 27, 2022 19:07
Show Gist options
  • Save colejd/081780f0ea087712a711b302a26c67ef to your computer and use it in GitHub Desktop.
Save colejd/081780f0ea087712a711b302a26c67ef to your computer and use it in GitHub Desktop.
Horizontal SwiftUI divider with content embedded in center
/// Embeds its content between two horizontal dividers.
struct Davider<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
HStack {
Divider().axis(.horizontal)
content
Divider().axis(.horizontal)
}
}
}
// MARK: - Private extensions
private extension Divider {
func axis(_ axis: Axis?) -> some View {
modifier(DividerAxisModifier(axis: axis))
}
}
private struct DividerAxisModifier: ViewModifier {
let axis: Axis?
@ViewBuilder func body(content: Content) -> some View {
if let a = axis {
switch a {
case .horizontal: VStack { content }
case .vertical: HStack { content }
}
} else {
content
}
}
}
// MARK: - Previews
struct Davider_Previews: PreviewProvider {
static var previews: some View {
Davider {
Text("TEXT")
}
.previewLayout(PreviewLayout.sizeThatFits)
.padding()
.frame(width: 300)
}
}
@colejd
Copy link
Author

colejd commented Jan 27, 2022

Here's how the preview looks:

Dave's Cool Divider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment