UIButton with GradientLayer obscures image and darkens gradient

Christian A. Strømmen picture Christian A. Strømmen · Nov 12, 2011 · Viewed 8.2k times · Source

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];

Answer

Christian A. Strømmen picture Christian A. Strømmen · Nov 24, 2011

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!)