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

1

5
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 ?

Filomena answered 11/12, 2020 at 9:25 Comment(0)
C
14

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)
    }
}
Cumulation answered 11/12, 2020 at 9:35 Comment(2)
Wow that was so easy not sure why my mind didn't triggered.Filomena
Change path.addLine(to: CGPoint(x: rect.width, y: rect.height)) to: path.addLine(to: CGPoint(x: 0, y: rect.height)). Otherwise the line has a slight bend towards the right.Britisher

© 2022 - 2024 — McMap. All rights reserved.