Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set gradient on UIButton in iOS swift?

I have a UIButton. I want to set the gradient of button as below.

enter image description here

I have tried below code but it does not set the color as per screenshot.

 func applyGradient(colours: [UIColor]) -> Void {
        self.applyGradient(colours: colours, locations: nil)
    }

    func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
    }
like image 963
TechChain Avatar asked Jan 28 '23 21:01

TechChain


1 Answers

You can simply do it like:

extension UIButton
{
    func applyGradient(colors: [CGColor])
    {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

Setting the gradient on UIButton:

self.button.applyGradient(colors: [UIColor.green.cgColor, UIColor.black.cgColor])
like image 173
PGDev Avatar answered Feb 01 '23 00:02

PGDev