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

时间:2013-03-24 11:38:20

标签: 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;

}

2 个答案:

答案 0 :(得分:13)

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

// both set to clear color eventually
_label.layer.backgroundColor = [UIColor grayColor].CGColor;
_label.backgroundColor = [UIColor clearColor];

到此:

// both set to gray eventually
_label.backgroundColor = [UIColor clearColor];
_label.layer.backgroundColor = [UIColor grayColor].CGColor;

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

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

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

答案 1 :(得分:0)

不要忘记将视图的isOpaque值设置为false。在IB中默认为true。

相关问题