Why drawRect: work without calling [super drawrect: rect]?

I override drawRect: in one of my views and it works even without calling [super drawrect: rect]. How it works?

- (void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetBlendMode(context, kCGBlendModeDestinationOver); [[UIColor clearColor] setFill]; UIRectFill(CGRectMake(0,0,100,100)); } 
+8
ios core-graphics
source share
4 answers

From the documentation:

"By default, the implementation of this method does nothing. That use technologies such as Core Graphics and UIKit, for presentation they must override this method and implement their drawing code there."

Also from the documentation ..

"If you subclass UIView directly, your implementation of this method does not need to be called super. However, if you subclass a different presentation class, you should call super at some point in your implementation."

Documentation Link

I assume your superclass is UIView. Therefore, it works even if [super drawrect: rect] is not called. Because drawRect: because UIView does nothing. Therefore, in this case, it does not matter whether or not you call [super drawrect: rect].

+19
source share

Basically, this works because the mechanism that sets up the graphics context for drawing, etc., does not live in the implementation of UIView -drawRect: (empty).

This mechanism really lives somewhere, of course, let it pretend that in every UIView there is such an internal method as this: the names of methods, functions and properties are invented to protect the innocent:

 - (void)_drawRectInternal:(CGRect)rect { // Setup for drawing this view. _UIGraphicsContextPushTransform(self._computedTransform); // Call this object implementation of draw (may be empty, or overridden). [self drawRect:rect]; // draw our subviews: for (UIView * subview in [self subviews]) { [subview _drawRectInternal:rect]; } // Teardown for this view. _UIGraphicsContextPopTransform(); } 

This is a cleaner way to build frameworks than relying on a subclass to do the right thing in a general redefinition, where misuse would lead to very mysterious bad behavior. (And that would not be really possible, since drawing and the tear-off step might be required for drawing.)

+5
source share

Thank you .. There is no need to call super, because the superclass is here UIView, whose drawRect: does nothing.

In general, we call setNeedDisplay if we want to call drawRect to draw.

-one
source share

I am sure that subview is not working without calling [super drawrect: rect]. If you need to save a supervisor drawing, you must add [super drawrect: rect] in the subview: rect listing, or you will replace the drawing.

-one
source share

All Articles