2013-03-04 87 views
1

在iOS上,我將CALayer添加到UITableViewCell的圖層。這是我第一次使用CALayer,它只是應該改變表格單元格的背景顏色。我的目標是(1)學習如何使用CALayer,以及(2)使用Instruments來測試繪圖是否比我當前的實現更快,這會降低CGContextFillRect的速度。使用CALayer設置UITableViewCell背景顏色

Technical Q&A 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 = ...行,我所有其他繪圖仍然存在,但在黑色背景上。

我錯過了什麼?

+2

試着用'insertSublayer:atIndex:0',而不是'addSublayer:'。這將該圖層置於子圖層數組的底部。操作系統使用圖層'zPosition'和子圖層數組中的相對位置來確定哪個圖層可見,哪些圖層被遮擋。 – 2013-03-04 22:47:28

+0

@Aaron Brager你爲什麼在這裏使用'CALayer'?你想用它做什麼,你不能在'UIView'上做什麼? – 2013-03-05 02:39:00

+0

@DanielMartín那沒用。在索引0和1處,我只是得到一個黑色背景; 2和更高我沒有看到我的繪圖。 – 2013-03-05 07:14:36

回答

3

爲什麼你得到意外行爲的原因是因爲UITableViewCell的相對複雜的視圖層次:

- UITableViewCell 
    - contentView 
    - backgroundView 
    - selectedBackgroundView 

每當在UITableViewCell定義自定義繪圖程序,你應該在contentView層次結構中這樣做。這包括繼承UIView,覆蓋-drawRect:,並將其作爲子視圖添加到contentView中。

爲什麼你的背景顏色是你的榜樣被忽略的原因是由於您的加入您的CALayerUITableViewCell的層的子層。這被UITableViewCellcontentView所掩蓋。

但是,由於某種原因,您希望在此處使用CALayer。我想了解爲什麼它沒有UIView沒有的東西。你可以在你的contentView上設置backgroundColor,而不是做這個迂迴的事情。

下面是一個例子使用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]]; //use whatever color you wish. 

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

@end 
+2

謝謝。這個改變使我的'drawRect'函數的執行時間減少了幾秒鐘,現在我的表格以每秒56-58幀而不是40-45 FPS的速度滾動。 – 2013-03-07 21:41:05

+2

沒有'initWithFrame:'方法,'setBackgroundColor:'有'CGColorRef',而不是'UIColor'。 – pr1001 2015-05-12 22:06:24