Search code examples
iosuiviewswift4uibezierpathcashapelayer

How to add dashed border on View's frame not on bounds [Swift]


I am trying to add a dashed border on View which will always be on the view's frame not on it's bound .

My code :

func addDashedBorder() {

    let color = UIColor.red.cgColor
    shapeLayer = CAShapeLayer()
    let frameSize = self.bounds.size
    let shapeRect = CGRect(x:0 , y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.frame = 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: self.frame, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}

Result
enter image description here

I don't want to rotate the Border on View if we rotate the view . it should indicate how much space its is taking on view .

Expectation

enter image description here


Solution

  • You need to take two view i.e inner and outer view. Inner view (rotation view) should be in the subview of outer view. The frame must be same for both views. Use the following line of code -

    @IBOutlet weak var viewOuter: UIView! //static outer view
    @IBOutlet weak var viewInner: UIView! // View that will be use for rotation
    
    func addDashedBorder() {
    
        let color = UIColor.red.cgColor
        let shapeLayer = CAShapeLayer()
        let frameSize = viewInner.bounds.size
        let shapeRect = CGRect(x:0 , y: 0, width: frameSize.width, height: frameSize.height)
        shapeLayer.frame = 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 = kCALineJoinRound
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(roundedRect: viewInner.frame, cornerRadius: 5).cgPath
        self.viewOuter.layer.addSublayer(shapeLayer)
    
    }