自定义 UIButton class - 按钮边框外的渐变

custom UIButton class - gradient going out off button borders

我正在做自定义 UIButton class,我希望它具有渐变背景。我的渐变颜色看起来很完美,但超出了按钮边框

我的代码:

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    func setup(){
        layer.cornerRadius = 25.0
        layer.borderWidth = 1
        gradientLayer.frame = layer.bounds
        addShadow()
    }
    
    private lazy var gradientLayer: CAGradientLayer = {
        let color1 = UIColor(red: 254.0/255.0, green: 79.0/255.0, blue: 50.0/255.0, alpha: 1.0).cgColor
        let color2 = UIColor(red: 255.0/255.0, green: 26.0/255.0, blue: 107.0/255.0, alpha: 1.0).cgColor
        let gradient = CAGradientLayer()
        gradient.frame = layer.bounds
        gradient.colors = [color1, color2]
        gradient.startPoint = CGPoint(x: 0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1, y: 0.5)
        gradient.locations = [0,1]
        gradient.cornerRadius = 25
        layer.insertSublayer(gradient, at: 0)
        return gradient
    }()
    
    func addShadow(){
        layer.shadowOpacity = 1
        layer.shadowRadius = 1.0
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize(width: 0, height: 3)
    }
    
}

它是这样的:

从设置中删除 gradientLayer.frame 并添加 layoutSubviews

同时设置 self.bounds 而不是 layer.bounds

override func layoutSubviews() {
      super.layoutSubviews()
      gradientLayer.frame = self.bounds // < Here
}

注意:从 var gradientLayer 中删除 gradient.frame = layer.bounds。不需要。

只需覆盖 layerClass 即可避免调整大小问题(自动调整大小有约束)

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    override class var layerClass: AnyClass {
        CAGradientLayer.self
    }
    
    var gradientLayer: CAGradientLayer {
        layer as! CAGradientLayer
    }
    
    func setup(){
        gradientLayer.cornerRadius = 25.0
        gradientLayer.borderWidth = 1
        let color1 = UIColor(red: 254.0/255.0, green: 79.0/255.0, blue: 50.0/255.0, alpha: 1.0).cgColor
        let color2 = UIColor(red: 255.0/255.0, green: 26.0/255.0, blue: 107.0/255.0, alpha: 1.0).cgColor
        gradientLayer.colors = [color1, color2]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.locations = [0,1]
        gradientLayer.shadowOpacity = 1
        gradientLayer.shadowRadius = 1.0
        gradientLayer.shadowColor = UIColor.black.cgColor
        gradientLayer.shadowOpacity = 1
        gradientLayer.shadowOffset = CGSize(width: 0, height: 3)
    }
    
}