Search code examples
objective-ccocoa-touchiphone-sdk-3.0uiview

UIView subclass draws background despite completely empty drawRect: - why?


So, I have a custom UIView subclass which enables drawing of rounded edges. The thing draws perfectly, however the background always fills the whole bounds, despite clipping to a path first. The border also draws above the rectangular background, despite the fact that I draw the border in drawRect: before the background. So I removed the whole content of drawRect:, which is now virtually empty - nevertheless the background gets drawn!

Anybody an explanation for this? I set the backgroundColor in Interface Builder. Thanks!


Solution

  • Sorry for this monologue. :)

    The thing is that the UIView's layer apparently draws the background, which is independent from drawRect:. This is why you can't get rid of the background by overriding drawRect:.

    You can either override - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx and make the layer draw whatever you want, or you override - (void) setBackgroundColor:(UIColor *)newColor and don't assign newColor to backgroundColor, but to your own ivar, like myBackgroundColor. You can then use myBackgroundColor in drawRect; to draw the background however you like.


    Overriding setBackgroundColor:

    Define an instance variable to hold your background color, e.g. myBackgroundColor. In your init methods, set the real background color to be the clearColor:

    - (id) initWithCoder:(NSCoder *)aDecoder
    {
        if ((self = [super init...])) {
            [super setBackgroundColor:[UIColor clearColor]];
        }
        return self;
    }
    

    Override:

    - (void) setBackgroundColor:(UIColor *)newColor
    {
        if (newColor != myBackgroundColor) {
            [myBackgroundColor release];
            myBackgroundColor = [newColor retain];
        }
    }
    

    Then use myBackgroundColor in your drawRect: method. This way you can use the color assigned from Interface Builder (or Xcode4) in your code.