ios - Sublayer 只在 initWithFrame 中创建时绘制,不在 initWithCoder 中绘制

标签 ios objective-c uiview cashapelayer initwithframe

我有一个带有子层(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/

相关文章:

ios - Json Values Append Array 但 ViewDidLoad 看起来是空的

ios - enumerateKeysAndObjectsWithOptions 未按预期工作

ios - 如何在收到远程通知时唤醒未运行的应用程序

ios - 如何在 objective c 中缩放和滑动来自 webservise 的多个图像

ios - UIView & UIViewController 应用程序设计

ios - 分页时优化数组数据大小

ios - 将快照字典从 firebase 数据库保存到类对象

iphone - 当一个 subview 大小发生变化时,如何调整其他 subview 和父 View 的大小

ios - 屏幕旋转时的多个 NSNotifications

ios - 创建 uiview 动画 "drone"或 "slave"?