Swift Recipe

Add dashed line border around a UIView


Introduction

We all know that we can add a simple border around the view very easily in Swift. If you want to add a dashed border, you are at the right spot. This post very quickly describes how easily you can add dashed line border around a UIView.

Implementation

To add dashed line border around a UIView, we will create a UIView extension:

extension UIView {
    func addDashedBorder() {
        let color = UIColor.black.cgColor
        
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
        
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 4).cgPath
        
        self.layer.addSublayer(shapeLayer)
    }
}

Here, we created a CAShapeLayer which we will add as a sub layer of the view’s layer.

We set the bounds of the shape layer same as the view’s frame itself.

We set the colors for the border as strokeColor and clear color as the fillColor aka background color of the shape layer.

Most important part to notice here is the lineDashPattern property, that’s where the real magic is.

As mentioned in the Apple Documentation:

The dash pattern is specified as an array of NSNumber objects that specify the lengths of the painted segments and unpainted segments, respectively, of the dash pattern.

For example, passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment. Passing the values [10,5,5,5] sets the pattern to a 10-unit painted segment, a 5-unit unpainted segment, a 5-unit painted segment, and a 5-unit unpainted segment.

Source: https://developer.apple.com/documentation/quartzcore/cashapelayer/1521921-linedashpattern

To use this, call the addDashedBorder() on your view.

yourView.addDashedBorder()

You can use the same extension on UILabel or almost any view.

Output:

Dashed UIView
Dashed Border around the view

That’s all on how to add dashed line border around UIView.


Learn how to add animations to your SwiftUi app here!

Checkout another quick article on How To Add Splash Screen in SwiftUI.

If you want to learn how to use SwiftUI in your existing app, then you can read it here!

or If you want to learn how to use and convert your UIViewControllers in SwiftUI, then you can read it here!


Like it? Share with your friends!

0 Comments

Your email address will not be published. Required fields are marked *