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

前端 未结 4 1252
悲&欢浪女
悲&欢浪女 2021-02-04 11:23

I\'m overriding drawRect: in one of my views and it works even without calling [super drawrect:rect]. How does that work?

- (void)drawRect:(CGRect)rect{  
    C         


        
4条回答
  •  北海茫月
    2021-02-04 11:55

    Basically, it works because the machinery that sets up the graphics context for drawing, etc, doesn't live in the UIView implementation of -drawRect: (which is empty).

    That machinery does live somewhere, of course, let's pretend in every UIView there's some internal method like this-- 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's 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 of building the frameworks than relying on a subclasser to do the right thing in a common override, where getting it wrong would have result in very puzzling bad behavior. (And this wouldn't really be possible at all since the draw might need a setup and a teardown step.)

提交回复
热议问题