To draw graphics on the view you have to create a subclass of the UIView object and override the drawRect method. Do this as follows:

Create The Subclass File

New File

Select the ‘Objective-C’ class icon and click Next.

Change the Subclass of: option to ‘UIView’ and click Next

Save the class (e.g. name as #Draw2D_iPhone instead of #ViewController_iPhone)

Set The View Controller To Use It

Open the original #ViewController.xib file and select the view. In the Identity Inspector properties change the Class setting from ‘UIView’ to our new class named #Draw2D_iPhone

In the #Draw2D_iPhone.m file create this function to carry out the drawing:

    - (void) drawRect:(CGRect)rect

Note you can’t call this function directly, but you can trigger it in your main ViewController file by using:

    [self.view setNeedsDisplay];

Draw Lines

     //Get the CGContext from this view
     CGContextRef context = UIGraphicsGetCurrentContext();

     //Set the stroke (pen) color
     CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
     //Set the width of the pen mark
     CGContextSetLineWidth(context, 5.0);

     // Draw a line
     //Start at this point
     CGContextMoveToPoint(context, 10.0, 30.0);

     //Give instructions to the CGContext
     //(move "pen" around the screen)
     CGContextAddLineToPoint(context, 310.0, 30.0);
     CGContextAddLineToPoint(context, 310.0, 90.0);
     CGContextAddLineToPoint(context, 10.0, 90.0);

     //Draw it

Draw Rectangle

     //Get the CGContext from this view
     CGContextRef context = UIGraphicsGetCurrentContext();

     //Draw a rectangle
     CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
     //Define a rectangle
     CGContextAddRect(context, CGRectMake(10.0, 150.0, 60.0, 120.0));     //X, Y, Width, Height
     //Draw it