Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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                action:@selector(goBack)      forControlEvents:UIControlEventTouchUpInside]; [backButton setBackgroundColor:[UIColor clearColor]]; CAGradientLayer *buttonGradient = [CAGradientLayer layer]; buttonGradient.frame = backButton.bounds; buttonGradient.colors = [NSArray arrayWithObjects:                          (id)[[UIColor colorWithRed:.0                                               green:.166                                                blue:.255                                               alpha:1] CGColor],                           (id)[[UIColor colorWithRed:.0                                               green:.113                                                blue:.255                                               alpha:1] CGColor],                           nil]; [buttonGradient setCornerRadius:backButton.frame.size.width / 2]; [backButton.layer insertSublayer:buttonGradient                          atIndex:0]; [backButton setImage:[UIImage imageNamed:@"backarrow.png"]             forState:UIControlStateNormal]; [backButton setEnabled:NO]; [topbarView addSubview:backButton]; 
like image 251
Christian A. Strømmen Avatar asked Nov 12 '11 18:11

Christian A. Strømmen


1 Answers

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.

Objective-C:

[button bringSubviewToFront:button.imageView]  

Swift 4.1:

button.bringSubview(toFront:button.imageView!) 
like image 173
Christian A. Strømmen Avatar answered Sep 28 '22 12:09

Christian A. Strømmen