Search code examples
swiftxcodeuiviewuibezierpathcgpoint

How to Add Line between two UIView centers in Swift?


As you can see in the Image attached, there are red and green Views on the screen, I want to add a Line between them. How can I do that?


Solution

  •   func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
        let line = CAShapeLayer()
        let linePath = UIBezierPath()
        linePath.move(to: start)
        linePath.addLine(to: end)
        line.path = linePath.cgPath
        line.strokeColor = UIColor.red.cgColor
        line.lineWidth = 1
        line.lineJoin = CAShapeLayerLineJoin.round
        self.view.layer.addSublayer(line)
    }
    

    Usage: - addLine(fromPoint: yourFirstView.center, toPoint: yourSecondView.center)

    Make sure your views are accessible while calling this function