0

サブレイヤー (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]

4

1 に答える 1

1

initWithFrame:との違いは、ビューがストーリーボード/ペン先から作成されたときに呼び出されるinitWithCoder:ことです。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;
}
于 2014-08-18T15:47:50.633 に答える