Dashed line border around UIView

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

How do I add dashed line border around UIView.

Something Like this

\"\"

23条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 04:40

    Swift 4.2

    Based off rmooney's answer as a UIView extension with configurable parameters that have default values set.

    Note this does not work if the view has self.translatesAutoresizingMaskIntoConstraints = false

    extension UIView {
      func addDashedBorder(_ color: UIColor = UIColor.black, withWidth width: CGFloat = 2, cornerRadius: CGFloat = 5, dashPattern: [NSNumber] = [3,6]) {
    
        let shapeLayer = CAShapeLayer()
    
        shapeLayer.bounds = bounds
        shapeLayer.position = CGPoint(x: bounds.width/2, y: bounds.height/2)
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = width
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
        shapeLayer.lineDashPattern = dashPattern
        shapeLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
    
        self.layer.addSublayer(shapeLayer)
      }
    }
    

提交回复
热议问题