Dashed line border around UIView

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

How do I add dashed line border around UIView.

Something Like this

\"\"

23条回答
  •  离开以前
    2020-12-02 04:37

    • Swift 5

    • Works with autolayout

    • Works with the corner radius

    import UIKit
    
        class DashedBorderView: UIView {
    
        private let dashedLineColor = UIColor.black.cgColor
        private let dashedLinePattern: [NSNumber] = [6, 3]
        private let dashedLineWidth: CGFloat = 4
    
        private let borderLayer = CAShapeLayer()
    
        init() {
            super.init(frame: CGRect.zero)
    
            borderLayer.strokeColor = dashedLineColor
            borderLayer.lineDashPattern = dashedLinePattern
            borderLayer.backgroundColor = UIColor.clear.cgColor
            borderLayer.fillColor = UIColor.clear.cgColor
            borderLayer.lineWidth = dashedLineWidth
            layer.addSublayer(borderLayer)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func draw(_ rect: CGRect) {
            borderLayer.frame = bounds
            borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: layer.cornerRadius).cgPath
        }
    }
    

提交回复
热议问题