我试图理解为什么我不能将UILabel的图层作为子图层添加到单独的UIView对象中的另一个图层。
- (void)addNumber:(NSInteger)number toLayer:(CALayer *)layer {
UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))];
[numberLabel setFont:[UIFont boldSystemFontOfSize:12]];
[numberLabel setText:[NSString stringWithFormat:@"%d", number]];
/* if I change the BackgroundColor to an opaque color it renders as a solid black rect.
* No matter what color I choose
* Setting it as clear then it is transparent
*/
[numberLabel setBackgroundColor:[UIColor clearColor]];
[numberLabel setTextAlignment:NSTextAlignmentCenter];
[numberLabel setTextColor:[UIColor blackColor]];
CALayer *numberLayer = numberLabel.layer;
/* However creating a CATextLayer is successful
CALayer *numberLayer = [CATextLayer layer];
[numberLayer setFont:(__bridge CFTypeRef)([UIFont boldSystemFontOfSize:12])];
[numberLayer setBounds:CGRectMake(0, 0, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))];
[numberLayer setString:[NSString stringWithFormat:@"%d", number]];
[numberLayer setAlignmentMode:kCAAlignmentCenter];
[numberLayer setForegroundColor:[[UIColor whiteColor] CGColor]];
*/
[numberLayer setPosition:CGPointMake(CGRectGetMidX(layer.bounds),
CGRectGetMidY(layer.bounds) + CGRectGetMidY(numberLayer.bounds))];
[layer addSublayer:numberLayer];
}
但是,如果我要创建一个CATextLayer,它可以正常工作。 (见注释掉的代码)
我的理解是每个UIView子类都由根CALayer支持。 我是否应该无法将根CALayer添加到另一个CALayer的子层层次结构中?
感谢您的帮助
答案 0 :(得分:1)
numberLayer是指向numberLabel.layer的指针,因此它是一个单个实例 - 图层的单个实例或UIView只能是一个父级的子级而不是多个。
答案 1 :(得分:0)
CALayer符合NSCoding协议,因此您可以编码现有的CALayer实例,然后通过解码第一个实例来创建新的CALayer实例。