Last active
January 27, 2022 19:07
-
-
Save colejd/081780f0ea087712a711b302a26c67ef to your computer and use it in GitHub Desktop.
Horizontal SwiftUI divider with content embedded in center
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
/// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's how the preview looks: