gpt4 book ai didi

ios - 使用 CALayer 设置 UITableViewCell 背景颜色

转载 作者:行者123 更新时间:2023-12-01 19:12:54 25 4
gpt4 key购买 nike

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

(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 = ...线,我所有的其他绘图仍然存在,但在黑色背景上。

我错过了什么?

最佳答案

您出现意外行为的原因是 UITableViewCell的相对复杂的 View 层次结构:

- UITableViewCell
- contentView
- backgroundView
- selectedBackgroundView

每当您在 UITableViewCell 中定义自定义绘图例程时, ,您应该在 contentView 内这样做等级制度。这涉及子类 UIView , 覆盖 -drawRect: , 并将其作为 subview 添加到 contentView .

在您的示例中您的背景颜色被忽略的原因是由于您添加了 CALayer作为 UITableViewCell 的子层的层。这被 UITableViewCell 所掩盖。的 contentView .

但是,出于某种原因,您希望使用 CALayer这里。我想了解为什么因为它没有任何 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

关于ios - 使用 CALayer 设置 UITableViewCell 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com