Skip to content

Instantly share code, notes, and snippets.

@Mcrich23
Created May 12, 2025 01:47
Show Gist options
  • Save Mcrich23/a180cd59c5c4cae3bb0b160ff728fc62 to your computer and use it in GitHub Desktop.
Save Mcrich23/a180cd59c5c4cae3bb0b160ff728fc62 to your computer and use it in GitHub Desktop.
A dynamic dashed line view for SwiftUI
import SwiftUI
enum DashedLineAlignment {
case horizontal
case vertical
}
struct DashedLine: View {
let alignment: DashedLineAlignment
let spacing: CGFloat
let dashes: Int?
let size: CGFloat
@State var implicitDashes: Int = 5
init(alignment: DashedLineAlignment, spacing: CGFloat = 25, dashes: Int? = nil, size: CGFloat = 4) {
self.alignment = alignment
self.spacing = spacing
self.dashes = dashes
self.size = size
}
var body: some View {
GeometryReader { geo in
VHStack(spacing: spacing) {
ForEach(0..<(dashes ?? implicitDashes), id: \.self) { _ in
rectangle
}
}
.onAppear {
switch alignment {
case .horizontal:
implicitDashes = Int(geo.size.width / 40)
case .vertical:
implicitDashes = Int(geo.size.height / 60)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
}
}
@ViewBuilder
var rectangle: some View {
switch alignment {
case .horizontal:
Rectangle()
.frame(height: size)
case .vertical:
Rectangle()
.frame(width: size)
}
}
@ViewBuilder
func VHStack<Content: View>(spacing: CGFloat, @ViewBuilder content: () -> Content) -> some View {
switch alignment {
case .horizontal:
HStack(spacing: spacing, content: content)
case .vertical:
VStack(spacing: spacing, content: content)
}
}
}
#Preview("Vertical Dash") {
DashedLine(alignment: .vertical)
}
#Preview("Horizontal Dash") {
DashedLine(alignment: .horizontal)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment