0

Please i need some code to make a button background gradiente color, please i dont know how to make it. I have tried with layers and a public class like this code, but the class doesnt appear

public class GradientButton: UIButton {

override public func layoutSubviews() {
    super.layoutSubviews()
    layoutGradientButtonLayer()
}

// MARK: Private
private func layoutGradientButtonLayer() {
    let gradientLayer = CAGradientLayer()
    let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor
    let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor
    gradientLayer.colors = [color1, color2]
    gradientLayer.locations = [0.0, 1.0]
    self.layer.addSublayer(gradientLayer)
}

}

Juan Jose Rodrigo
  • 429
  • 2
  • 6
  • 14
  • Possible duplicate of [Set Background Gradient on Button in Swift](http://stackoverflow.com/questions/37903124/set-background-gradient-on-button-in-swift) – shallowThought Jan 14 '17 at 08:32

2 Answers2

1
extension UIView {
    func applyGradient(colours: [UIColor]) -> Void {
        self.applyGradient(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, atIndex: 0)
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var btn: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.btn.titleLabel?.textColor = UIColor.whiteColor()

        self.btn.applyGradient([UIColor.yellowColor(), UIColor.blueColor()])
        self.view.applyGradient([UIColor.yellowColor(), UIColor.blueColor(), UIColor.redColor()], locations: [0.0, 0.5, 1.0])
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
NiravS
  • 1,144
  • 1
  • 12
  • 24
0

I think you should set your gradientLayer.frame to self.bounds in layoutSubViews(), and it should be fine

Jerome Li
  • 1,492
  • 14
  • 20