How to Add Line between two UIView centers in Swift?

242 Views Asked by At

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?

1

There are 1 best solutions below

0
PRakash On BEST ANSWER
  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