25

How can I design programmatically UIButton like this gradient border color?

Gradient button]

Thanks for help

jomafer
  • 2,655
  • 1
  • 32
  • 47
m.akyol
  • 283
  • 1
  • 3
  • 7
  • I need gradient border color pls click to link : ) – m.akyol Apr 25 '16 at 09:19
  • http://stackoverflow.com/questions/15193993/how-to-make-a-gradient-border-of-uiview http://stackoverflow.com/questions/10200814/how-to-set-a-gradient-border-on-uiview , follow this link – Sheereen S Apr 25 '16 at 09:22

1 Answers1

61
let gradient = CAGradientLayer()
gradient.frame =  CGRect(origin: CGPointZero, size: self.myButton.frame.size)
gradient.colors = [UIColor.blueColor().CGColor, UIColor.greenColor().CGColor]

let shape = CAShapeLayer()
shape.lineWidth = 2
shape.path = UIBezierPath(rect: self.myButton.bounds).CGPath
shape.strokeColor = UIColor.blackColor().CGColor
shape.fillColor = UIColor.clearColor().CGColor
gradient.mask = shape

self.myButton.layer.addSublayer(gradient)

Swift 3 version:

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myButton.frame.size)
    gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]

    let shape = CAShapeLayer()
    shape.lineWidth = 2
    shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    self.myButton.layer.addSublayer(gradient)
gvuksic
  • 2,983
  • 3
  • 32
  • 37
  • 3
    It works, but is it possibly to make the corners rounded instead of being pointy ? – Ahmad Jul 21 '16 at 05:38
  • 1
    @Ahmad you can use the cornerRadius property – Hellojeffy Oct 07 '16 at 20:28
  • 12
    to add corner radius shape.path = UIBezierPath(roundedRect: self.myButton.bounds, cornerRadius: self.myButton.cornerRadius).cgPath – Sameh May 20 '18 at 16:15
  • 2
    And don't forget to add `self.myButton.clipsToBounds = true` for correct corner radius showing – Ivan Smetanin Dec 14 '18 at 07:03
  • 4
    To add corner radius in Swift 4.2 + , use following code: `myButton.layer.cornerRadius = 25 shape.path = UIBezierPath(roundedRect: myButton.bounds, cornerRadius: myButton.layer.cornerRadius).cgPath` The `cornerRadius` is the attribute of layer and not of UIButton. – Pankaj Kulkarni Dec 18 '18 at 19:57
  • how to add shadows to the gradient border views – nickypatson Jul 07 '20 at 12:41
  • why everyone hardcodes layer sizes on creation? People can't just take and use your code without of significant modifications – Gargo Jul 06 '23 at 14:36