Search code examples
swiftuibuttoncagradientlayer

GradientLayer shows outside the button


I'm developing in Swift and want to make a rounded button with a gradient layer on it. At the corner of the buttons the gradient layer shows outside of the button. How to fix?

This is the code I made for it:

    let newLayer = CAGradientLayer()
    newLayer.frame = button.bounds
    newLayer.colors = [UIColor.white.cgColor, UIColor.lightGray.cgColor]
    button.layer.insertSublayer(newLayer, at: 0)

    button.layer.cornerRadius = 10.0
    button.layer.borderWidth = 3.0
    button.layer.borderColor = UIColor.darkGray.cgColor
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOpacity = 1.0
    button.layer.shadowRadius = 5.0
    button.layer.shadowOffset = CGSize.init(width: 3, height: 3)

enter image description here


Solution

  • Just add one more line:

    button.clipsToBounds = true
    

    And your result will be:

    enter image description here