How to draw a line in the simplest way in swift

Try looking into UIBezierPath, it will help you a lot for drawing lines. Here is documentation. Here is an example:

override func drawRect(rect: CGRect) {
    let aPath = UIBezierPath()

    aPath.move(to: CGPoint(x:<#start x#>, y:<#start y#>))
    aPath.addLine(to: CGPoint(x: <#end x#>, y: <#end y#>))

    // Keep using the method addLine until you get to the one where about to close the path
    aPath.close()

    // If you want to stroke it with a red color
    UIColor.red.set()
    aPath.lineWidth = <#line width#>
    aPath.stroke()
}

Make sure you put this code in the drawRect, like in the example above.

If you need to update the drawing just call setNeedsDisplay() to update.

Leave a Comment