views:

34

answers:

1

I have a scene, called testScene, it works like this:

@interface testScene : myScene {
 IBOutlet UIView *subview;
 IBOutlet UIView *drawingCanvasView;
 IBOutlet UIButton *update;
}

- (void)updateDrawingCanvas: (id) sender;

and when the user click the button, update, it will run the updateDrawingCanvas method. So, I have a drawingCanvasView, which gave a drawingCanvas.h, and .m, it like this:

#import <UIKit/UIKit.h>


@interface DrawingCanvasView : UIView {
 CGImageRef image;

}

-(void)setNeedsDisplayInRect:(CGContextRef)context;

@end

In the DrawingCanvasView, I have a drawRect method like this:

 CGContextRef context = UIGraphicsGetCurrentContext();
 CGContextSetLineWidth(context, 2.0); 
 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
 CGContextMoveToPoint(context, 0.0f, 0.0f);
 CGContextAddLineToPoint(context, 100.0f, 100.0f); 
 CGContextStrokePath(context);

And I want the user click the button, and execute this, so I added a new method called setNeedsDisplayInRect:

 CGContextRef context = UIGraphicsGetCurrentContext();
 CGContextSetLineWidth(context, 2.0); 
 CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor); 
 CGContextMoveToPoint(context, 0.0f, 0.0f);
 CGContextAddLineToPoint(context, 200.0f, 200.0f); 
 CGContextStrokePath(context);

But I can't called that in my updateDrawingCanvas method, it work like this:

- (void)updateDrawingCanvas: (id) sender{
 NSLog(@"loaded");
 [DrawingCanvasView setNeedsDisplayInRect:UIGraphicsGetCurrentContext()];
}

It my logic / concept right? or something I did wrong, thx.

+3  A: 

No, you don't overwrite setNeedsDisplayInRect:. You implement the drawing code in drawRect: and when you call setNeedsDisplayInRect: the framework will ensure that your drawRect: gets called.

Marcelo Cantos
I can drawRect: , but I can't update the view... ...The system will call the drawRect again, if I called [DrawingCanvasView setNeedsDisplay]; again?
Tattat
What do you mean by "I can drawRect:"? You should never call `drawRect:`.
Marcelo Cantos
So, I should do everything about drawing in drawRect:, but I can't called the drawRect: directly?
Tattat
That's correct. Just call `setNeedsDisplayInRect:` or `setNeedsDisplay:` and the framework will call `drawRect:` for you.
Marcelo Cantos
Why Apple design the UIView in this way?
Tattat
Tattat: The documentation explains why. http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/WindowsandViews/WindowsandViews.html#//apple_ref/doc/uid/TP40007072-CH8-SW53
Peter Hosey