views:

1005

answers:

4

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!

A: 

This is easily reproducible:

Create a new View-Based iPhone Application. Create an UIView subclass and leave the drawRect: method completely empty. In Interface Builder, drag a UIView into the main view, assign it a background color and set the class of the view to your subclass. Save, build and run, and see, the view shows the background color.

I have circumvented this behaviour by overriding setBackgroundColor: and assigning the color to my own ivar, always leaving the backgroundColor property nil. This works, however I'm still wondering why this works this way.

Pascal
A: 

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 realBackgroundColor. You can then use realBackgroundColor in drawRect; to draw the background however you like.

Pascal
A: 

I hesitate to suggest this because I don't want to offend you, but have you set opaque to NO?

Craig
No offense taken, the question is actually a good one: Yes, opaque was set to NO. :)
Pascal
A: 

Here's an easier fix:

self.backgroundColor = [UIColor clearColor];
Tyler
Yes, that's what's accomplished by overriding setBackgroundColor:. I was more wondering why anything was drawn at all, despite drawRect: being empty. Answer was that the background is drawn in drawLayer:inContext:.
Pascal