How can I set the background of a UIButton to a CAGradientLayer?
I have tried the following:
func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors.map { $0.cgColor }
gradient.locations = locations
self.layer.insertSublayer(gradient, at: 0)
}
which I got from Set Background Gradient on Button in Swift
and then to use it:
let startButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Get Started", for: .normal)
button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
return button
}()
startButton.applyGradient(colors: [.red, .blue], locations: nil)
Also, I am setting the width of the button to the view's width and the height to 50.
However, when I run it, this is what I get:
The background gradient is not applied.