I have been playing with some of Apple’s example code for customizing UITableViewCells. I have run into some weird behavior that has left me completely confused about how backgroundColor works.
The following code is a much reduced version of Apple’s example custom UIView within custom UITableViewCell. The init function sets the background color to purple and then the drawRect sets the background color to green. I would expect to never see purple, but that is all I see. Through NSLog statements I know that the init method is being called for each of the cells, followed by drawRect being called for each of the cells. The green setting seems to be ignored. If I call [self setNeedsDisplay] any time after the initial load, the background is correctly set to green.
- (id)initWithFrame:(CGRect)frame {
counter = 0;
if ((self = [super initWithFrame:frame])) {
self.opaque = YES;
self.backgroundColor = [UIColor purpleColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
self.backgroundColor = [UIColor greenColor];
}
Can anyone explain to me why this would be happening like this?
Your
-drawRect:implementation doesn’t actually do any drawing, so it’s not going to change anything itself.Presumably, the drawing is being done by a layer associated with your view. It looks like, in your environment, the background-colored layer is doing its drawing before your
-drawRect:method is called. When the layer redraws, your-drawRect:method also happens to be called. So, after you change the background color, you don’t see any changes till the background layer draws again, which you can tell happened because your-drawRect:gets called again.If you want the color change to apply immediately, you need to mark your view as needing display, so that it will completely redraw with the changed background color.