Search code examples
swiftcgcontextuigraphicscontext

How do I draw a line in iOS swift in the viewDidLoad() function?


I keep getting the following error when trying to draw a green line in my viewDidLoad(). It is important that I do it here because it's in between new labels when they are being placed down. The error is:

<Error>: CGContextSetLineWidth: invalid context 0x0. If you want to see 
 the backtrace, 
 please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

The code for drawing the line(s) is below:

    let context = UIGraphicsGetCurrentContext()
                        CGContextSetLineWidth(context, 3.0)
                        CGContextSetStrokeColorWithColor(context,self.hexStringToUIColor("#008500").CGColor)
                        CGContextMoveToPoint(context, 0,CGFloat(top+40))
                        CGContextAddLineToPoint(context, CGFloat(screenWidth*2), CGFloat(top+40))
                        CGContextStrokePath(context)

Solution

  • From the comments it sounds like you just want to add a line to your user interface programmatically. To do that, just use a UIView to create the line. Set its backgroundColor to the color you want. The height you specify for the frame will be the thickness of the line.

    // Add a green line with thickness 1, width 200 at location (50, 100)
    let line = UIView(frame: CGRect(x: 50, y: 100, width: 200, height: 1))
    line.backgroundColor = UIColor.greenColor()
    self.view.addSubview(line)