我有一个带有子层(CAShapeLayer)和 subview (UILabel)的自定义 View 。当我在 initWithCoder 中创建图层并设置背景颜色时,它始终显示为黑色。但是,如果我将代码移至 initWithFrame
中,颜色就会成功显示。
我们不应该在initWithCoder
中创建子层吗?
这是让我的代码正常工作的唯一方法:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.colorLayer = [CAShapeLayer layer];
self.colorLayer.opacity = 1.0;
[self.layer addSublayer:self.colorLayer];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.textLabel = [[UILabel alloc] initWithFrame:self.bounds];
self.textLabel.font = [UIFont primaryBoldFontWithSize:12];
self.textLabel.textColor = [UIColor whiteColor];
self.textLabel.textAlignment = NSTextAlignmentCenter;
self.textLabel.backgroundColor = [UIColor clearColor];
[self addSubview:self.textLabel];
}
return self;
}
- (void)drawRect:(CGRect)rect {
//Custom drawing of sublayer
}
更新:
结果在我的drawRect
中我设置了错误的填充颜色。我应该使用 colorLayer.fillColor = myColor.CGColor
而不是 [myColor setFill]
然后 [path fill]
最佳答案
initWithFrame:
之间的区别和 initWithCoder:
是那个initWithCoder:
当从 Storyboard / Nib 创建 View 时调用。
如果您以编程方式添加它,例如:
UIView *v = [[UIView alloc] initWithFrame:...];
[self.view addSubview:v];
initWithFrame:
被称为。
好主意是创建基本的 init 方法并在两个 init 中调用它。以这种方式,当以编程方式或在 Storyboard 中添加 View 时,初始化会在两种情况下设置所有属性。
例如:
-(void)baseInit {
self.colorLayer = [CAShapeLayer layer];
self.colorLayer.opacity = 1.0;
//... other initialisation
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self baseInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self baseInit];
}
return self;
}
关于ios - Sublayer 只在 initWithFrame 中创建时绘制,不在 initWithCoder 中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367136/