为什么我不能直接设置视图的底层图层的背景颜色?

时间:2019-07-26 09:10:17

标签: ios objective-c cocoa-touch

我创建一个名为MyCustomLabel的类,它是UIView的子类,并且重写了它的layerClass函数以返回CATextLayer类。我发现,如果要在layerWillDraw:函数中设置该图层的背景色,必须先设置该视图的背景色,否则无论我设置为图层的背景色如何,背景色都只是黑色。

@interface MyCustomLabel : UIView

@end

@implementation MyCustomLabel

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // if I do not set it here, the final background color
        // is black, in layerWillDraw function, setting of layer's backgound color has no use
        self.backgroundColor = [UIColor greenColor];
    }
    return self;
}

+ (Class)layerClass {
    return [CATextLayer class];
}

- (void)layerWillDraw:(CALayer *)layer {
    CATextLayer *textLayer = (CATextLayer *)layer;
    textLayer.fontSize = 20.f;
    textLayer.alignmentMode = kCAAlignmentCenter;
    textLayer.string = @"MyCustomLabel";
    textLayer.foregroundColor = [UIColor redColor].CGColor;
    textLayer.borderColor = [UIColor blueColor].CGColor;
    textLayer.borderWidth = 5.f;

    textLayer.backgroundColor = [UIColor greenColor].CGColor;
}


0 个答案:

没有答案