Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a dashed line in swift?

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.

like image 438
A. Steiness Avatar asked Aug 15 '16 19:08

A. Steiness


1 Answers

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.

like image 55
Fan Jin Avatar answered Sep 21 '22 21:09

Fan Jin