On iOS, I am adding a CALayer to a UITableViewCell's layer. This is my first time using CALayer, and it is simply supposed to change the background color of the table cell. My goal is (1) to learn how to use CALayer, and (2) to test using Instruments whether the drawing is faster than my current implementation, which slows down on CGContextFillRect.
(Technical Q&A QA1708 was the catalyst for all this.)
Current Implementation (works)
- (void)drawRect:(CGRect)r
{
UIColor *myColor = [self someColor];
[myColor set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context, r); // draw the background color
// now draw everything else
// [...]
}
Attempted New Implementation (doesn't work)
#import <QuartzCore/QuartzCore.h>
@implementation MyCell {
CALayer *backgroundLayer;
}
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// [...other stuff here too]
backgroundLayer = [[CALayer alloc] init];
[[self layer] addSublayer:backgroundLayer];
}
return self;
}
- (void)drawRect:(CGRect)r {
backgroundLayer.frame = CGRectMake(0, 0, r.size.width, r.size.height);
[backgroundLayer setBackgroundColor:[self someColor]];
// now draw everything else
// [...]
}
I see the correct colors, but none of the other drawing (I'm assuming the custom drawing ends up behind my new layer).
If I remove the backgroundLayer.frame = ...
line, all of my other drawing is still there, but on a black background.
What am I missing?