美文网首页
UILabel 圆角

UILabel 圆角

作者: 一只大码农 | 来源:发表于2020-07-06 16:32 被阅读0次
label.backgroundColor = UIColor.redColor;
label.layer.cornerRadius = 5;

很多人发现这样设置后圆角不生效,必须加上下面代码才会有圆角

label.layer.masksToBounds = YES;

但是这样做就会触发离屏渲染,可直接这样做防止离屏渲染

label.layer.backgroundColor = UIColor.redColor.CGColor;

为啥会这样,UIView UIButton 都不用设置layer.masksToBounds = YES
那是因为UILabellayer是一个私有类 _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;
}
image.png

_contentLayer.frame的比label的要大

相关文章

网友评论

      本文标题:UILabel 圆角

      本文链接:https://www.haomeiwen.com/subject/qmxgqktx.html