I have a rounded UIView
and I have added a dashed line stroke to it.
,,,
var view = CAShapeLayer()
view.strokeColor = UIColor.red.cgColor
view.lineDashPattern = [2, 2]
view.frame = addphotoView.bounds
view.fillColor = nil
view.path = UIBezierPath(rect: addphotoView.bounds).cgPath
view.cornerRadius = 16
view.masksToBounds = true
addphotoView.layer.addSublayer(yourViewBorder)
But view.cornerRadius
is not working as expected:
Corner is wiped out.
Select the view that you want to round and open its Identity Inspector. In the User Defined Runtime Attributes section, add the following two entries: Key Path: layer. cornerRadius , Type: Number, Value: (whatever radius you want)
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.
If you start with a regular UIView it has square corners. You can give it round corners by changing the cornerRadius property of the view's layer . and smaller values give less rounded corners. Both clipsToBounds and masksToBounds are equivalent.
To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer. First of all, let's add an UIImageView Object in our storyboard. Or let's create one programmatically.
You should round the Layer
s path
.
like this:
borderLayer.path = UIBezierPath(roundedRect: addphotoView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 16, height: 16)).cgPath
You can move all this logic into an extension:
extension UIView {
@discardableResult
func addLineDashedStroke(pattern: [NSNumber]?, radius: CGFloat, color: CGColor) -> CALayer {
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = color
borderLayer.lineDashPattern = pattern
borderLayer.frame = bounds
borderLayer.fillColor = nil
borderLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
layer.addSublayer(borderLayer)
return borderLayer
}
}
addphotoView.addLineDashedStroke(pattern: [2, 2], radius: 16, color: UIColor.gray.cgColor)
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