子层仅在initWithFrame中创建时绘制,而不是initWithCoder

时间:2014-08-18 15:42:56

标签: ios objective-c uiview cashapelayer initwithframe

我有一个带有子图层(CAShapeLayer)和子视图(UILabel)的自定义视图。当我在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]

1 个答案:

答案 0 :(得分:1)

initWithFrame:initWithCoder:之间的区别在于,当从storyboard / nib创建视图时,会调用initWithCoder:

如果以编程方式添加它,例如:

UIView *v = [[UIView alloc] initWithFrame:...];
[self.view addSubview:v];

initWithFrame:被调用。

好主意是创建基本init方法并在init中调用它。通过这种方式,当以编程方式或在故事板中添加视图时,初始化会在两个场景中设置所有属性。

例如:

-(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;
}
相关问题