0

I've got a project with some buttons that are in a UIStackView. Each of the buttons has a backgroundImage. Everything renders as desired, but I'd like to put a gradient layer in front of the backgroundImage that's semi-transparent so the text on the button has a little more contrast.

I'm attempting to use this code in viewDidLoad to add a semi-transparent gradient on front of each UIButton's backgroundImage:

buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5)]
// gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5).cgColor]
// gradientLayer.colors = [UIColor.orange]
// gradientLayer.colors = [UIColor.orange.cgColor]
buttonArray.forEach({$0.imageView?.layer.insertSublayer(gradientLayer, at: 0)})

As it stands, nothing gets added. I tried changing the color to something without a alpha value and changing the desired color to a .cgColor. No dice. Thank you for reading. I welcome your suggestions how to put a gradientLayer in front of a UIButton's backgroundImage.

I based my attempt off code found here

Adrian
  • 16,233
  • 18
  • 112
  • 180

1 Answers1

0

I think you have to specify more than one color, as well as the bounds of the layer:

    let buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]

    for button in buttonArray {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [UIColor(white: 0.5, alpha: 0.5).cgColor, UIColor(white: 1.0, alpha: 0.5).cgColor]
        gradientLayer.frame = (button?.bounds)!
        button?.layer.insertSublayer(gradientLayer, at: 0)
    }
CodeNinja
  • 616
  • 4
  • 18