Home > Mobile >  How to set gradient color in UIbutton?
How to set gradient color in UIbutton?

Time:08-26

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.

CodePudding user response:

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)
  }
  • Related