iOS给view添加虚线边框

直接上代码

  fileprivate func drawDashLine(_ view: UIView) {
            let shapeLayer:CAShapeLayer = CAShapeLayer()
            shapeLayer.bounds = view.bounds
            shapeLayer.position = CGPoint(x: view.frame.width / 2, y: view.frame.height / 2)
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = USColor.c302.cgColor
            
            shapeLayer.lineWidth = 1
            shapeLayer.lineJoin = kCALineJoinRound
            shapeLayer.lineDashPhase = 0
            shapeLayer.lineDashPattern = [NSNumber(value: 2), NSNumber(value: 2)]
            
            let path:CGMutablePath = CGMutablePath()
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: view.frame.width, y: 0))
            shapeLayer.path = path
            
            view.layer.addSublayer(shapeLayer)
        }

给某个view设置虚线边框需要再layoutSubViews中进行,不然获取不到该view的frame,如果使用自动布局,需要设置该view的width

override func layoutSubviews() {
            super.layoutSubviews()
            
            self.drawDashLine(self.lineView)
        }

可以给UIView加上extension

public func drawDashLine() {
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        
        shapeLayer.bounds = self.bounds
        shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.red
        
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPhase = 0
        shapeLayer.lineDashPattern = [NSNumber(value: 2), NSNumber(value: 2)]
        
        let path:CGMutablePath = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: self.frame.width, y: 0))
        shapeLayer.path = path
        
        self.layer.addSublayer(shapeLayer)
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容