Tariq
Tariq

Reputation: 9979

SwiftUI - How to make a vertical dotted line using Shape?

struct DottedLine: Shape {
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: 0))
        return path
    }
}

DottedLine()
                .stroke(style: StrokeStyle(lineWidth: 1, dash: [2]))
                .frame(height: 1)
                .foregroundColor(Color.red)

This will create a horizontal dotted line. But how to make it vertical ? If I put Divider() in HStack then it become vertical but how to achieve the same with Dotted line ?

Upvotes: 7

Views: 5123

Answers (1)

Asperi
Asperi

Reputation: 257693

Make DottedLine react both on width and height and configure as needed in place of useage:

demo

struct DottedLine: Shape {
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        return path
    }
}

struct TestDottedLineView: View {
    var body: some View {
        DottedLine()
            .stroke(style: StrokeStyle(lineWidth: 1, dash: [2]))
            .frame(width: 1, height: 100)
            .foregroundColor(Color.red)
    }
}

Upvotes: 16

Related Questions