Isha Balla
Isha Balla

Reputation: 763

How to add a dashed border for any particular edge of a UIView?

How can I add a dashed border in certain side of the UIView only?Have referred to Dashed line border around UIView link, but I am kind of confused while giving the path for all the edges of a view.ok so, this is my code for adding a straight line border in particular side of a view:

 I want this as my output screen

func addRightBorder(with color: UIColor, andWidth borderWidth: CGFloat,view:UIView) {

            let border = UIView()
            border.backgroundColor = color
            border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
            border.frame = CGRect(x: view.frame.size.width - borderWidth, y: 0, width: borderWidth, height: view.frame.size.height)

            //border.addDashedLine(color: UIColor.red)
            border.addDashedLine(color: UIColor.red)
            view.addSubview(border)
        }*

How can I achieve the same thing but for dashed/dotted lines?

Upvotes: 0

Views: 1213

Answers (1)

Abhishek
Abhishek

Reputation: 995

In one of my app, I also needed a similar thing and I created UIView Extension.

Take a look at my code snippet,

extension UIView {
func removeDashedLine() {
    _ = layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
}

func addDashedLine(_ path: UIBezierPath ,pattern : [NSNumber] = [1, 5], color: UIColor = UIColor.red) {

    self.backgroundColor = UIColor.clear

    let shapeLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.name = "DashedTopLine"
    shapeLayer.frame = shapeRect
    //shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = pattern

    shapeLayer.path = nil
    shapeLayer.path = path.cgPath
    self.layer.insertSublayer(shapeLayer, at: 0)

}
}

It may not do exactly what you want but should help you

Upvotes: 1

Related Questions