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;
}
To use this, call the addDashedBorder() on your view. You can use the same extension on UILabel or almost any view. That's all on how to add dashed line border around UIView. Learn how to add animations to your SwiftUi app here!
Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With