1
votes

What I am trying to get is the a custom UIButton that has a gradient border (just the border is gradient) and rounded corners. I almost got to where I wanted to be, but having issues with the corners. Here is what I currently have: enter image description here

Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myButton.frame.size)
    gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.cornerRadius = 15

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

    self.myButton.clipsToBounds = true
    self.myButton.layer.cornerRadius = 15
    self.myButton.layer.addSublayer(gradient)
}

So the question is how do I display corners with gradient?

1
Can you check if setting gradient.maskToBounds = true ? works - Gihan

1 Answers

4
votes

The problem is with the mask, try to remove shape.cornerRadius = 15 and change this:

shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath

to this:

shape.path = UIBezierPath(roundedRect: self.myButton.bounds.insetBy(dx: 2.5, dy: 2.5), cornerRadius: 15.0).cgPath

Play with the values of the insets and cornerRadius to achieve your desired result.