label.backgroundColor = UIColor.redColor;
label.layer.cornerRadius = 5;
很多人发现这样设置后圆角不生效,必须加上下面代码才会有圆角
label.layer.masksToBounds = YES;
但是这样做就会触发离屏渲染,可直接这样做防止离屏渲染
label.layer.backgroundColor = UIColor.redColor.CGColor;
为啥会这样,UIView
UIButton
都不用设置layer.masksToBounds = YES
那是因为UILabel
的layer
是一个私有类 _UILabelLayer
, 它的内部还有一个 _UILabelContentLayer *_contentLayer
, 设置UILabel
的背景颜色只影响_contentLayer.contents
的背景颜色,然而CAlayer
的圆角在没有设置layer.masksToBounds = YES
只影响自身的边框和背景颜色, 所以我们直接设置UILabel.layer.cornerRadius
时背景颜色没圆角。
可这样验证,创建一个label
,点击后改变_contentLayer
的背景颜色
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 100, 200, 30)];
label.text = @"这是一个label";
label.backgroundColor = UIColor.redColor;
label.userInteractionEnabled = YES;
[label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]];
[self.view addSubview:label];
}
- (void)handleTap:(UITapGestureRecognizer*) tap
{
CALayer *layer = [tap.view.layer valueForKey:@"_contentLayer"];
layer.backgroundColor = UIColor.greenColor.CGColor;
}

_contentLayer.frame
的比label
的要大
网友评论