May you please assist, i have created a gradient which i have added to a button but now the button image i had set using storyboard is no longer displaying. My code is as follows:
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 function for the actual gradient implementation is as follows:
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 like below
the red will be the gradient and the white image is the one i want to display
You may move the button's imageView to the top position with bringSubview(toFront:)
if let imageView = button.imageView {
    productsAndServicesButton.bringSubviewToFront(imageView)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With