srikanth Kumar
srikanth Kumar

Reputation: 43

Draw a dotted line with full width in swift?

I am trying to create a dotted line programatically. However the line doesn't go all the way across the screen.

I have been using this SO answer to help me construct my dotted line. This is the output that I get.

OUTPUT

Here is my code

extension UIView{
    func addDashedBorder() {
        //Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 2
        // 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
        shapeLayer.lineDashPattern = [2,3]

        let path = CGMutablePath()
        path.addLines(between: [CGPoint(x: 0, y: 0),
                                CGPoint(x: self.frame.width, y: 0)])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)


    }
}

How can I fix my code so that the line goes across the whole screen?

Upvotes: 1

Views: 2108

Answers (2)

Yervand Saribekyan
Yervand Saribekyan

Reputation: 502

Give frame to CAShapeLayer

extension UIView{
    func addDashedBorder() {
        //Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.bounds
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 2
        // 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
        shapeLayer.lineDashPattern = [2,3]

        let size = shapeLayer.frame.size
        let rightTop = CGPoint.zero
        let leftTop = CGPoint(x: size.width, y: 0)
        let leftBottom = CGPoint(x: size.width, y: size.height)
        let rightBottom = CGPoint(x: 0, y: size.height)

        let path = CGMutablePath()
        path.addLines(between: [rightTop, leftTop, rightBottom, rightTop])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)


    }
}

Upvotes: 0

Grimxn
Grimxn

Reputation: 22507

Use self.bounds.width rather than self.frame.width.

From UIView's documentation:

frame

The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.

whereas:

bounds

The bounds rectangle, which describes the view’s location and size in its own coordinate system.

Upvotes: 1

Related Questions