Dashed line border around UIView

后端 未结 23 2401
粉色の甜心
粉色の甜心 2020-12-02 04:16

How do I add dashed line border around UIView.

Something Like this

\"\"

23条回答
  •  心在旅途
    2020-12-02 04:33

    For those of you working in Swift, this class extension on UIView makes it easy. This was based on sunshineDev's answer.

    extension UIView {
      func addDashedBorder() {
        let color = UIColor.red.cgColor
    
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
    
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
    
        self.layer.addSublayer(shapeLayer)
        }
    }
    

    To use it:

    anyView.addDashedBorder()
    

提交回复
热议问题