I have two sibling views: a gray label and a green button, button is underneath. For some reason, I need to set label.backgroundColor
to clear color and set label.layer.backgroundColor
to grey. And button color is green. I expect to see grey on screen (because label is on top of button). But all I see is green (color of button). Why?
EDIT: relevant code
// 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;
}
Finally I found the solution: simply reverse the order of this two lines:
// both set to clear color eventually
_label.layer.backgroundColor = [UIColor grayColor].CGColor;
_label.backgroundColor = [UIColor clearColor];
to this:
// both set to gray eventually
_label.backgroundColor = [UIColor clearColor];
_label.layer.backgroundColor = [UIColor grayColor].CGColor;
The reason is that for UILabel, (not UIView though, more on it later) setting its background color will set it's layer's background color to nil. But if we set label background color first, and set layer background color later, then both go their own ways, then we would see label background color on screen.
But for UIView, it's a totally different story: view background color and its layer's background color is the same thing. Therefore whichever set last will prevail.
However, I cannot find anything about above observation in documentation. Hope someone could step in and help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With