I am trying to create a button with a gradient color, but I can't seem to make it work. No color is applied to the borderColor property of my button. I tried implementing the code suggested by another SO post, but it does not work. Not sure why. Can someone help me understand why?
The code that I am using to change the layout of my button is:
// Constraints
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
myButton.heightAnchor.constraint(equalToConstant: myButton.height).isActive = true
myButton.widthAnchor.constraint(equalToConstant: myButton.width).isActive = true
// Layout
myButton.backgroundColor = UIColor.black
myButton.tintColor = UIColor.white
myButton.layer.cornerRadius = callButtonHeightAndWidth.height / 2
myButton.layer.borderWidth = 10
myButton.setTitle("Test", for: .normal)
myButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Regular", size: 27)
I tried to extend UIView with a function I call setGradientBorderWidthColor
and the code looks like:
func setGradientBorderWidthColor(button: UIButton)
{
let gradientColor = CAGradientLayer()
gradientColor.frame = CGRect(origin: CGPoint.zero, size: button.frame.size)
gradientColor.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 3
shape.path = UIBezierPath(rect: button.bounds).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradientColor.mask = shape
button.layer.addSublayer(gradientColor)
}
I also tried to just place the same code above in the viewDidLoad
function in my ViewController, but that did not work either. Any suggestions?
Edit 1:
Playing with the code and the suggestions provided I ended up with this. The issue is that whenever I add a corner radius to the button, the edges are cut off.