Search code examples
iosobjective-ciphoneuiview

Dashed line border around UIView


How do I add dashed line border around UIView.

Something Like this


Solution

  • Updated with Swift

    func appendDashedBorder() {
            let borderColor = UIColor.black.cgColor
            
            let yourViewShapeLayer: CAShapeLayer = CAShapeLayer()
            let yourViewSize = yourView.frame.size
            let yourViewShapeRect = CGRect(x: 0, y: 0, width: yourViewSize.width, height: yourViewSize.height)
            
            yourViewShapeLayer.bounds = yourViewShapeRect
            yourViewShapeLayer.position = CGPoint(x: yourViewSize.width/2, y: yourViewSize.height/2)
            yourViewShapeLayer.fillColor = UIColor.clear.cgColor
            yourViewShapeLayer.strokeColor = borderColor
            yourViewShapeLayer.lineWidth = 1
            yourViewShapeLayer.lineJoin = CAShapeLayerLineJoin.round
            yourViewShapeLayer.lineDashPattern = [4,2]
            yourViewShapeLayer.path = UIBezierPath(roundedRect: yourShapeRect, cornerRadius: 5).cgPath
            
            yourView.layer.addSublayer(yourViewShapeLayer)
        }
    

    You can add this method to UIView's extension and use it globally.

    Old Answer in Objective C

    You can set the border with this pattern using Layer and Bezier path like below examples.

    Objective-C

    CAShapeLayer *yourViewBorder = [CAShapeLayer layer];
    yourViewBorder.strokeColor = [UIColor blackColor].CGColor;
    yourViewBorder.fillColor = nil;
    yourViewBorder.lineDashPattern = @[@2, @2];
    yourViewBorder.frame = yourView.bounds;
    yourViewBorder.path = [UIBezierPath bezierPathWithRect:yourView.bounds].CGPath;
    [yourView.layer addSublayer:yourViewBorder];
    

    Swift 3.1

    var yourViewBorder = CAShapeLayer()
    yourViewBorder.strokeColor = UIColor.black.cgColor
    yourViewBorder.lineDashPattern = [2, 2]
    yourViewBorder.frame = yourView.bounds
    yourViewBorder.fillColor = nil
    yourViewBorder.path = UIBezierPath(rect: yourView.bounds).cgPath
    yourView.layer.addSublayer(yourViewBorder)
    

    You can also set different types of design using pattern image like below example.

    [yourView.layer setBorderWidth:5.0];
    [yourView.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"DotedImage.png"]] CGColor]];///just add image name and create image with dashed or doted drawing and add here
    

    Here you've to add <QuartzCore/QuartzCore> framework in the project and import it with below line in YourViewController.m file.

    #import <QuartzCore/QuartzCore.h>