Set Background Gradient on Button in Swift

Your code works fine. You just have to remember to set the gradient’s frame every time. It is better to just make the gradient category also set the frame of the view for you.

That way you don’t forget and it applies fine.

import UIKit

extension UIView {

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


    func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> CAGradientLayer {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
        return gradient
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var btn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.btn.applyGradient(colours: [.yellow, .blue])
        self.view.applyGradient(colours: [.yellow, .blue, .red], locations: [0.0, 0.5, 1.0])
    }


}

Buttons are views. You apply gradients to it the same way you would apply it to any other view.

Picture Proof:
enter image description here

Video Proof:
https://i.imgur.com/ssDTqPu.mp4

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)