1

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?

Grimxn
  • 22,115
  • 10
  • 72
  • 85

2 Answers2

1

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.

Grimxn
  • 22,115
  • 10
  • 72
  • 85
  • No even I change frame to bounds also showing the same error. – srikanth Kumar Nov 25 '19 at 03:19
  • Then I suspect that the answer lies in your storyboard - is the UIView constrained to fill the safe area, or does it just happen to be the same size as the simulated device in the storyboard? (because it wouldn't then resize when shown on a real device with different dimensions...) – Grimxn Nov 25 '19 at 10:25
0

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)


    }
}