How to make a dashed line in swift?

A. Steiness picture A. Steiness · Aug 15, 2016 · Viewed 37.2k times · Source

I want to know how to make a dashed line in swift like this: - - - - - - - - instead of a regular straight line like this: ----------------, I know that i can make multiple lines but that will require so much unnecessary code if i can just write it in 1 line. Btw it has to be in CoreGraphics.

Answer

Fan Jin picture Fan Jin · Mar 15, 2018

Swift 4

@IBOutlet var dashedView: UIView!

func drawDottedLine(start p0: CGPoint, end p1: CGPoint, view: UIView) {
    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.lightGray.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.lineDashPattern = [7, 3] // 7 is the length of dash, 3 is length of the gap.

    let path = CGMutablePath()
    path.addLines(between: [p0, p1])
    shapeLayer.path = path
    view.layer.addSublayer(shapeLayer)
}

Call function

drawDottedLine(start: CGPoint(x: dashedView.bounds.minX, y: dashedView.bounds.minY), end: CGPoint(x: dashedView.bounds.maxX, y: dashedView.bounds.minY), view: dashedView)

With the above you will have a straight line, you can also change points as you wish, for example if you change the end point's y from dashedView.bounds.minY to dashedView.bounds.maxY you will have diagonal.

If you will use it in a subclass of UIView you won't have the outlet so you will use it with self instead.