Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: layer background color not showing when view background color is clear color

Tags:

ios

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;

}
like image 679
Philip007 Avatar asked Dec 04 '22 11:12

Philip007


1 Answers

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.

like image 101
Philip007 Avatar answered May 21 '23 04:05

Philip007