UIButton with GradientLayer obscures image and darkens gradient UIButton with GradientLayer obscures image and darkens gradient ios ios

UIButton with GradientLayer obscures image and darkens gradient


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


Alternatively, you can insert the gradient layer below the image view's layer

CAGradientLayer* gradient = [CAGradientLayer layer];// ...[button.layer insertSublayer:gradient below:button.imageView.layer];


SWIFT 3

Here goes an example: (Based on Neil answer)

    let layer = CAGradientLayer()    layer.frame = CGRect(x: 0, y: 0, width: myButtonOutlet.layer.frame.size.width, height: myButtonOutlet..layer.frame.size.height)    layer.colors = [UIColor.white.cgColor, pixelColorReceta.cgColor]    layer.masksToBounds = true    layer.cornerRadius = myButtonOutlet.layer.cornerRadius    myButtonOutlet.layer.insertSublayer(layer, below: myButtonOutlet..imageView?.layer)

Happy coding :)