UIView with a Dashed line

后端 未结 8 1427
我寻月下人不归
我寻月下人不归 2020-11-28 06:22

What I have:

\"enter

To create this line, I basically have a

8条回答
  •  温柔的废话
    2020-11-28 06:52

    Swift 2.2

    dropping this in here to save others time..

    extension UIView {
        func addDashedLine(color: UIColor = UIColor.lightGrayColor()) {
            layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
            self.backgroundColor = UIColor.clearColor()
            let cgColor = color.CGColor
    
            let shapeLayer: CAShapeLayer = CAShapeLayer()
            let frameSize = self.frame.size
            let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
    
            shapeLayer.name = "DashedTopLine"
            shapeLayer.bounds = shapeRect
            shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
            shapeLayer.fillColor = UIColor.clearColor().CGColor
            shapeLayer.strokeColor = cgColor
            shapeLayer.lineWidth = 1
            shapeLayer.lineJoin = kCALineJoinRound
            shapeLayer.lineDashPattern = [4, 4]
    
            let path: CGMutablePathRef = CGPathCreateMutable()
            CGPathMoveToPoint(path, nil, 0, 0)
            CGPathAddLineToPoint(path, nil, self.frame.width, 0)
            shapeLayer.path = path
    
            self.layer.addSublayer(shapeLayer)
        }
    }
    

提交回复
热议问题