Skip to content

Instantly share code, notes, and snippets.

@odemolliens
Created October 5, 2016 11:37
Show Gist options
  • Save odemolliens/56f4ec07ae0a0dd63da47ff1f80b32a9 to your computer and use it in GitHub Desktop.
Save odemolliens/56f4ec07ae0a0dd63da47ff1f80b32a9 to your computer and use it in GitHub Desktop.
iOS Swift dashed lines extension
public let kShapeDashed : String = "kShapeDashed"
extension UIView {
func removeDashedBorder(_ view: UIView) {
view.layer.sublayers?.forEach {
if kShapeDashed == $0.name {
$0.removeFromSuperlayer()
}
}
}
func addDashedBorder(width: CGFloat? = nil, height: CGFloat? = nil, lineWidth: CGFloat = 2, lineDashPattern:[NSNumber]? = [6,3], strokeColor: UIColor = UIColor.red, fillColor: UIColor = UIColor.clear) {
var fWidth: CGFloat? = width
var fHeight: CGFloat? = height
if fWidth == nil {
fWidth = self.frame.width
}
if fHeight == nil {
fHeight = self.frame.height
}
let shapeLayer:CAShapeLayer = CAShapeLayer()
let shapeRect = CGRect(x: 0, y: 0, width: fWidth!, height: fHeight!)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: fWidth!/2, y: fHeight!/2)
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = lineDashPattern
shapeLayer.name = kShapeDashed
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
self.layer.addSublayer(shapeLayer)
}
}
@dushansri
Copy link

Can you explain how it works on dynamic view?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment