iOS adds dotted border to UIView

see code

 extension UIView{
    
    
    
    /*
     width:虚线的宽度
     length:虚线的长度
     space:虚线间的间距
     cornerRadius:view圆角
     color:虚线的颜色
     */
    func swiftDrawBoardDottedLine(width:CGFloat,
                                  length:CGFloat,space:CGFloat,cornerRadius:CGFloat,color:UIColor){
    
    
          self.layer.cornerRadius = cornerRadius
          let borderLayer =  CAShapeLayer()
          borderLayer.bounds = self.bounds
          
          borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY);
          borderLayer.path = UIBezierPath(roundedRect: borderLayer.bounds, cornerRadius: cornerRadius).cgPath
          borderLayer.lineWidth = width / UIScreen.main.scale
          
          //虚线边框---小边框的长度
          borderLayer.lineDashPattern = [length,space]  as [NSNumber]? //前边是虚线的长度,后边是虚线之间空隙的长度
          borderLayer.lineDashPhase = 0.1
          //实线边框
          
          borderLayer.fillColor = UIColor.clear.cgColor
          borderLayer.strokeColor = color.cgColor
          self.layer.addSublayer(borderLayer)
     }
}

use

  override func viewDidLoad() {
    
    
        super.viewDidLoad()
        view.backgroundColor = .brown
        let v = UIView.init(frame: CGRect.init(x: 100, y:200 , width: 240, height: 80))
        v.backgroundColor = .gray
        v.swiftDrawBoardDottedLine(width: 3,length: 7, space: 4, cornerRadius: 8, color: .white)
        view.addSubview(v)
    }

The effect diagram is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43259805/article/details/123347515