问题描述
我试图理解为什么我不能将UILabel的图层作为子图层添加到单独的UIView对象中的另一个图层。
I'm trying to understand why I can't add a UILabel's layer as a sublayer to another layer in a separate UIView object.
- (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,它可以正常工作。 (请参阅注释掉的代码)
However, if I was to create a CATextLayer instead, it works fine. (see commented out code)
我的理解是,每个UIView子类都由根CALayer支持。
我是否应该不能将该根CALayer添加到另一个CALayer的子层层次结构中?
My understanding is that every UIView subclass is backed by a root CALayer.Should I not be able to add that root CALayer to the sublayer hierarchy of another CALayer ?
感谢您的帮助
推荐答案
numberLayer是指向numberLabel.layer的指针,因此它是单个实例-图层或UIView的单个实例只能是一个父级的子级,而不是多个。
numberLayer is a pointer to numberLabel.layer, so it's a single instance - a single instance of a layer or UIView can only be a child to one parent, not multiple.
这篇关于将UILabel的图层添加到另一个图层(单独的UIView)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!