Search code examples
iosobjective-ciphoneswiftuiimageview

dashed border UIImageView swift


I'm trying to add a dashed border using CALayer on a UIImageView. I've found a method, but is that working in swift and how can i convert it to swift? o have another imageView which has a border so would be the best solution to use CALayer, so they look similar? How can i obtain this

obj-c code to swift?

- (CAShapeLayer *) addDashedBorderWithColor: (CGColorRef) color {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    CGSize frameSize = self.size;

    CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height);
    [shapeLayer setBounds:shapeRect];
    [shapeLayer setPosition:CGPointMake( frameSize.width/2,frameSize.height/2)];

    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    [shapeLayer setStrokeColor:color];
    [shapeLayer setLineWidth:5.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:
    [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
    [NSNumber numberWithInt:5],
  nil]];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0];
    [shapeLayer setPath:path.CGPath];

    return shapeLayer;
}

Solution

  • Ok, I would do simply like this in the custom view class:

    Updated for Swift 4

    class DashedBorderView: UIView {
    
        let _border = CAShapeLayer()
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        init() {
            super.init(frame: .zero)
            setup()
        }
    
        func setup() {
            _border.strokeColor = UIColor.black.cgColor
            _border.fillColor = nil
            _border.lineDashPattern = [4, 4]
            self.layer.addSublayer(_border)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            _border.path = UIBezierPath(roundedRect: self.bounds, cornerRadius:10).cgPath
            _border.frame = self.bounds
        }
    }