1

在 iOS 上,我将 CALayer 添加到 UITableViewCell 的层。这是我第一次使用CALayer,它只是为了改变表格单元格的背景颜色。我的目标是 (1) 学习如何使用 CALayer,以及 (2) 使用 Instruments 测试绘图是否比我当前的实现快,这会减慢 CGContextFillRect。

技术问答 QA1708是这一切的催化剂。)

当前实施(作品)

- (void)drawRect:(CGRect)r
{
    UIColor *myColor = [self someColor];
    [myColor set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextFillRect(context, r);  // draw the background color
    // now draw everything else
    // [...]

}

尝试了新的实现(不起作用)

#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
    // [...]
}

我看到正确的颜色,但没有其他绘图(我假设自定义绘图最终位于我的新图层后面)。

如果我删除这backgroundLayer.frame = ...条线,我的所有其他绘图仍然存在,但在黑色背景上。

我错过了什么?

4

1 回答 1

3

你得到意外行为的原因是因为UITableViewCell's 相对复杂的视图层次结构:

- UITableViewCell
   - contentView
   - backgroundView
   - selectedBackgroundView

每当您在 a 中定义自定义绘图例程时UITableViewCell,您都应该在contentView层次结构中这样做。这涉及子类化UIView、覆盖-drawRect:并将其作为子视图添加到contentView.

在您的示例中忽略背景颜色的原因是由于您将您添加CALayerUITableViewCell' 图层的子图层。这被UITableViewCell's所掩盖contentView

但是,出于某种原因,您希望在CALayer此处使用 a。我想了解为什么它没有 a 没有的任何东西UIView。你可以设置backgroundColor你的contentView而不是做这些迂回的事情。

CALayer这是一个按照您的要求使用的示例:

@implementation JRTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   if(self) {
      [self addCustomLayerToContentView];
   }
   return self;
}

- (void)addCustomLayerToContentView {
   CALayer *layer = [[CALayer alloc] initWithFrame:[self bounds]];  
   [layer setBackgroundColor:[[UIColor blueColor] cgColor]]; //use whatever color you wish.

   [self.contentView.layer addSublayer:layer];
}

@end
于 2013-03-05T02:43:21.143 回答