Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Button image not showing after adding gradient to button

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

like image 372
tapiwa takaindisa Avatar asked Apr 04 '17 11:04

tapiwa takaindisa


1 Answers

You may move the button's imageView to the top position with bring​Subview(to​Front:​)

if let imageView = button.imageView {
    productsAndServicesButton.bringSubviewToFront(imageView)
}
like image 121
Oleh Zayats Avatar answered Sep 28 '22 10:09

Oleh Zayats