iOS:当视图背景颜色为清晰颜色时,不显示图层背景颜色

Phi*_*007 4 ios

我有两个兄弟视图:灰色标签和绿色按钮,按钮位于下方.出于某种原因,我需要设置label.backgroundColor为清除颜色并设置label.layer.backgroundColor为灰色.按钮颜色为绿色.我希望在屏幕上看到灰色(因为标签位于按钮顶部).但我看到的只是绿色(按钮的颜色).为什么?

编辑:相关代码

// in my custom cell
-(void)awakeFromNib
{
    [super awakeFromNib];

    // customize label
    _label.layer.cornerRadius = 5;
    _label.layer.backgroundColor = [UIColor grayColor].CGColor;
    _label.backgroundColor = [UIColor clearColor];
    _label.layer.masksToBounds = NO;


    // customize button        
    // show shadow and rounded corner at the same time

    _button.backgroundColor = [UIColor clearColor];
    _button.layer.backgroundColor = [UIColor greenColor].CGColor;
    _button.layer.masksToBounds = NO;
    _button.layer.cornerRadius = 10.0f;

    self.layer.masksToBounds = NO;
    self.layer.cornerRadius = 10.0f;
    self.layer.shadowOpacity = 0.5f;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:_button.bounds cornerRadius:10.0f].CGPath;
    self.layer.shadowOffset = CGSizeMake(0.0f, 4.0f);
    self.layer.shadowRadius = 2.0f;

}
Run Code Online (Sandbox Code Playgroud)

Phi*_*007 16

最后我找到了解决方案:简单地颠倒这两行的顺序:

// both set to clear color eventually
_label.layer.backgroundColor = [UIColor grayColor].CGColor;
_label.backgroundColor = [UIColor clearColor];
Run Code Online (Sandbox Code Playgroud)

对此:

// both set to gray eventually
_label.backgroundColor = [UIColor clearColor];
_label.layer.backgroundColor = [UIColor grayColor].CGColor;
Run Code Online (Sandbox Code Playgroud)

原因是对于UILabel,(不是UIView,稍后会更多)设置其背景颜色会将其图层的背景颜色设置为nil.但是如果我们先设置标签背景颜色,然后再设置图层背景颜色,那么两者都采用自己的方式,然后我们会在屏幕上看到标签背景颜色.

但对于UIView来说,这是一个完全不同的故事:查看背景颜色及其图层的背景颜色是一回事.因此,以最后一个设定为准.

但是,我在文档中找不到任何关于上述观察的内容.希望有人可以介入并提供帮助.

  • 好的,但UILabel怎么样? (3认同)