How to make dotted/dashed line in iOS?

iOSApps/ApplicationsMobile Development

Knowing how to make dotted or dashed line is very important. You might develop a page where you ask user to enter fields, there you can represent the same with dotted line. Dotted line can also be used to highlight certain things in an application.

The most important use is in the navigation application. While designing the navigation application you must know how to draw the path and you might end up using dotted lines.

Let us see how we can achieve this functionality in iOS.

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “DottedLine”

Step 2 − In Main.storyboard add a UIView as shown, create @IBOutlet and name it dottedView.

Step 3 − Add the following code in your ViewController.swift, add the below extension.

extension UIView {
   func createDottedLine(width: CGFloat, color: CGColor) {
      let caShapeLayer = CAShapeLayer()
      caShapeLayer.strokeColor = color
      caShapeLayer.lineWidth = width
      caShapeLayer.lineDashPattern = [2,3]
      let cgPath = CGMutablePath()
      let cgPoint = [CGPoint(x: 0, y: 0), CGPoint(x: self.frame.width, y: 0)]
      cgPath.addLines(between: cgPoint)
      caShapeLayer.path = cgPath

Step 4 − From viewDidLoad method call the same function on dottedView object as show below

override func viewDidLoad() {
   self.dottedView.createDottedLine(width: 5.0, color: UIColor.cyan.cgColor)

If you notice we are passing the width and the color of the dotted line, you can customize the way you want to have the dotted line.

Step 5 - Run to see the effect.

Published on 08-Jul-2019 11:34:08