Swift: button image not showing after adding gradient to button

Can you help, I created a gradient that I added to the button, but now the button image that I set using the storyboard is no longer displayed. My code looks like this:

import UIKit

class MenuViewController: UIViewController {

    @IBOutlet weak var productsAndServicesButton: UIButton!

       override func viewDidLoad() {
        super.viewDidLoad()

        let bg = CAGradientLayer().redBackgroundGradient()
        bg.frame = self.productsAndServicesButton.bounds
        self.productsAndServicesButton.layer.insertSublayer(bg, at: 0)

   }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

      

the code with a function to implement the actual gradient looks like this:

import UIKit

extension CAGradientLayer {

    func redBackgroundGradient() -> CAGradientLayer{
        let startColor =  UIColor(red:0.82, green:0.13, blue:0.19, alpha:1.0)
        let centreColor = UIColor(red:0.65, green:0.04, blue:0.10, alpha:1.0)
        let endColor = UIColor(red:0.56, green:0.04, blue:0.09, alpha:1.0)

        let gradientColors : [CGColor] = [startColor.cgColor,centreColor.cgColor,endColor.cgColor]
        let gradientLocations : [Float] = [0.0,0.5,1.0]
        let gradientLayer : CAGradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientColors
        gradientLayer.locations = gradientLocations as [NSNumber]?

        return gradientLayer
    }


}

      

I want the image to appear on top of the gradient as shown below

red will be the gradient and white image will be the one I want to display

+3


source to share


1 answer


You can move the button imageView

in top position

with Output Subview (start :)



if let imageView = button.imageView {
    productsAndServicesButton.bringSubview(toFront: imageView)
}

      

+4


source







All Articles