Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 313
Pascal Avatar asked Oct 11 '09 17:10

Pascal


2 Answers

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.

like image 155
Pascal Avatar answered Sep 21 '22 02:09

Pascal


Here's an easier fix:

self.backgroundColor = [UIColor clearColor];
like image 39
Tyler Avatar answered Sep 21 '22 02:09

Tyler