views:

199

answers:

2

I am trying to draw a line

my Code is this

-(void) drawRect:(CGRect) rect
{
    NSLog(@"Reached Draw ARect Function");

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(ctx, 2.0);
    CGContextSetRGBStrokeColor(ctx, 1.0, 2.0, 0, 1); 
    CGContextMoveToPoint(ctx, 0, 0);
    CGContextAddLineToPoint( ctx, 100,100);

    CGContextStrokePath(ctx);

}

and i am calling from the viewDidLoad as follows

- (void)viewDidLoad {

    [super viewDidLoad];
    CGRect k = CGRectMake(1.0, 1.0, 100.0, 200.0);
    [self.view drawRect:k];

}

Can any one help me please?

+3  A: 

You should subclass a UIView and move your line drawing code to the drawRect: method, like you are doing (just hoping it's for a UIView subclass and not the UIViewController)

- (void)drawRect:(CGRect)rect {

   [super drawRect:rect];

   // Place your code here

}

You must also make sure you use the UIView subclass in InterfaceBuilder for the view you will be drawing into. You should not have to call this method yourself. If you want to animate something you should call the [view setNeedsDisplay]; to request a redraw of the view.



...and...you should add CGContextBeginPath(ctx); just before you call CGContextMoveToPoint

epatel
im subclassing UIViewController,how can i change it to UIView. or how to draw in a class that had inherited UIViewController[WAITING FOR THE ANSWER]
new_programmer
I made a small example here http://memention.com/SubclassedView.zip See the files SubclassView.h and .m
epatel
Thank you for the source code and your time.i will reply after checking it.
new_programmer
epatel, It worked... :DThank you very much. But i have one more problem .It will work only when we change the class of the view as "SubClassView".I am creating views programatically.[Description of my Problem]my MainView contain 3 buttons .When any of the button is pressed , will will load another view named "DetailedView"Button 1 and 2 will create a tableview in "DetailedView"Button 3 has to draw a line.[ please reply if you did not get what i mean ][sorry for my poor English][waiting for your reply]
new_programmer
Sorry I do not really understand what you want. Just to draw a line with a button click can be done in many many ways.
epatel
Sorry . leave it.I have added a new question in the following link"http://stackoverflow.com/questions/3638872/draw-a-layer-with-some-color-in-iphone-application"
new_programmer
A: 

You can't call drawRect directly.

Instead you call setNeedsDisplay on your UIView, return, and wait for the OS to call the UIView's drawRect with a proper context at some later time.

hotpaw2
please explain this answer
new_programmer