Ios 如何使用Swift编程渐变边框颜色按钮

Ios 如何使用Swift编程渐变边框颜色按钮,ios,iphone,uibutton,swift2,gradient,Ios,Iphone,Uibutton,Swift2,Gradient,如何以编程方式设计这种渐变边框颜色的UIButton ] 谢谢你的帮助 let gradient = CAGradientLayer() gradient.frame = CGRect(origin: CGPointZero, size: self.myButton.frame.size) gradient.colors = [UIColor.blueColor().CGColor, UIColor.greenColor().CGColor] let shape = CAShapeLayer

如何以编程方式设计这种渐变边框颜色的UIButton

]

谢谢你的帮助

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版本:

    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)

选中此项我需要渐变边框颜色请单击链接:),跟随此链接它可以工作,但是否可能使角变圆而不是变尖?@Ahmad您可以使用cornerRadius属性添加角半径形状。path=UIBezierPath(roundedRect:self.myButton.bounds,cornerRadius:self.myButton.cornerRadius).cgpath,不要忘记添加
self.myButton.clipstobunds=true
正确的角半径显示要在Swift 4.2+中添加角半径,请使用以下代码:
myButton.layer.cornerRadius=25 shape.path=UIBezierPath(roundedRect:myButton.bounds,cornerRadius:myButton.layer.cornerRadius).cgPath
角半径是图层的属性,而不是UIButton的属性。