Christian A. Strømmen Christian A. Strømmen - 1 year ago 112
iOS Question

UIButton with GradientLayer obscures image and darkens gradient

I have an UIButton here where I'd like to have a gradient as the background below the image (symbol with transparent background), but I'm facing two different problems.

First of the CAGradientLayer seems to overlay on top of the image no matter how I try to add it, obscuring the image completely.

Secondly the gradient itself seems to be darkened a lot, like the button was disabled, which it isn't.

Here's my code:

self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 35, 28, 28)];
[backButton addTarget:self
[backButton setBackgroundColor:[UIColor clearColor]];
CAGradientLayer *buttonGradient = [CAGradientLayer layer];
buttonGradient.frame = backButton.bounds;
buttonGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:.0
alpha:1] CGColor],
(id)[[UIColor colorWithRed:.0
alpha:1] CGColor],
[buttonGradient setCornerRadius:backButton.frame.size.width / 2];
[backButton.layer insertSublayer:buttonGradient
[backButton setImage:[UIImage imageNamed:@"backarrow.png"]
[backButton setEnabled:NO];
[topbarView addSubview:backButton];

Answer Source

So I managed to get around this by doing a [button bringSubviewToFront:button.imageView] after adding the gradient. Seems that no matter what I do the new layer will add on top of the imageView, so I need to push that to the front afterwards.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download