0
- (void)drawRect:(CGRect)rect
{
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(c, red);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 150.0f, 200.0f);
CGContextSetLineWidth(c, 5.0f);
CGContextAddLineToPoint(c, 50,300);
CGContextAddLineToPoint(c, 260,300);
CGContextClosePath(c);
}

Here is my viewwillappear

-(void)viewWillAppear:(BOOL)animated
{
    [self.view setNeedsDisplay];         
}

However, the view cannot draw the line and just white blank.

Ramaraj T
  • 5,184
  • 4
  • 35
  • 68
Alan Lai
  • 1,296
  • 2
  • 12
  • 16
  • Your code makes no sense. What's `c`? If this were your real code, the compiler would complain. Either that, or you're setting `c` as an ivar in some meaningless way. You can only get the drawing context from inside `drawRect`, and your code is not doing that. So the problem is not that iOS can't draw; it's that *you* don't know how to draw. My book teaches you: http://www.apeth.com/iOSBook/ch15.html – matt Nov 22 '12 at 04:13
  • c = uigraphicgetccurrentcontext – Alan Lai Nov 22 '12 at 04:30
  • But that's not in your code. So is your code just a lie? – matt Nov 22 '12 at 04:46
  • never mind, i knew what the problem – Alan Lai Nov 22 '12 at 05:50

3 Answers3

1

Did you try this one?

- (void)drawRect:(CGRect)rect
    [super drawRect:rect];

    CGContextRef context    = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0);


    CGContextMoveToPoint(context, 0,0); //start at this point

    CGContextAddLineToPoint(context, 20, 20); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
1

It seems you are using the drawRect method in a UIViewController subclass. But drawRect method applies only to the UIView subclass.

If I am right then do the following. Otherwise seee @Anoop Vaidya's answer. That should be working.

Subclass an UIView, do all your stuff in drawRect and add that view to your view controller.

@interface myView : UIView
{

}
@end

@implementation myView

- (void)drawRect:(CGRect)rect{

}

@end

    -(void)viewWillAppear:(BOOL)animated
{
    myView *view1  = [[myView alloc]init];
    self.view =  view1;        
}
Ramaraj T
  • 5,184
  • 4
  • 35
  • 68
1

you can use this drawRect Tutorial which is very useful for head start. about your issue, make sure that your UIView that you are drawing at is the view that is visible, maybe you are overriding the UIView or there are other views on top of this view and because of that it is not possible to see the changes. also maybe you forgot to Initialize the View before showing it.

Milad Rezazadeh
  • 1,473
  • 12
  • 34