Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set gradient color in UIbutton?

How we can set gradient colour in UIButton using swift?

I have tried this:

func addGradient(btn : UIButton){
    let color1 = UIColor(red: 221.0/255, green: 96.0/255, blue: 129.0/255, alpha: 1.0).cgColor
    let color2 = UIColor(red: 171.0/255, green: 74.0/255, blue: 141.0/255, alpha: 1.0).cgColor
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [color2,color1 ]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.6)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.6)
    btn.layer.insertSublayer(gradientLayer, at: 0)
}

it’s not working properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try below code hope it will fix your issue:

Uses:

override func viewDidAppear(_ animated: Bool) {
  yesBtn.clipsToBounds = true
  yesBtn.addGradient(btn: yesBtn)
}

Extension:

func addGradient(btn : UIButton){
  let color1 = UIColor(red: 221.0/255, green: 96.0/255, blue: 129.0/255, alpha: 1.0).cgColor
  let color2 = UIColor(red: 171.0/255, green: 74.0/255, blue: 141.0/255, alpha: 1.0).cgColor
  let gradientLayer = CAGradientLayer()
  gradientLayer.frame = btn.bounds
  gradientLayer.colors = [color2,color1 ]
  gradientLayer.locations = [0.0, 1.0]
  gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.6)
  gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.6)
  btn.layer.insertSublayer(gradientLayer, at: 0)
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading