如何将渐变层宽度设置为与按钮宽度相同?

how to set gradient layer width to be the same as button width?

我是iOS开发的新手,我想用这个可设计的渐变圆角按钮class

@IBDesignable
class GradientButton: UIButton {
    let gradientLayer = CAGradientLayer()

    @IBInspectable
    var topGradientColor: UIColor? {
        didSet {
            setGradient(topGradientColor: topGradientColor, bottomGradientColor: bottomGradientColor)
        }
    }

    @IBInspectable
    var bottomGradientColor: UIColor? {
        didSet {
            setGradient(topGradientColor: topGradientColor, bottomGradientColor: bottomGradientColor)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var fullRounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }



    @IBInspectable var cornerRadiusOfButton : CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadiusOfButton
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = fullRounded ? (frame.size.height / 2) : cornerRadiusOfButton
    }


    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }

    private func setGradient(topGradientColor: UIColor?, bottomGradientColor: UIColor?) {
        if let topGradientColor = topGradientColor, let bottomGradientColor = bottomGradientColor {
            gradientLayer.frame = bounds
            gradientLayer.colors = [topGradientColor.cgColor, bottomGradientColor.cgColor]
            gradientLayer.borderColor = layer.borderColor
            gradientLayer.borderWidth = layer.borderWidth
            gradientLayer.cornerRadius = layer.cornerRadius
            layer.insertSublayer(gradientLayer, at: 0)
        } else {
            gradientLayer.removeFromSuperlayer()
        }
    }
}

但这是结果:

正如你所见,渐变层按钮的宽度不正确。

这里是我使用的约束布局:

我想让那个渐变层和原来按钮的宽度一样,我怀疑是这一行有问题

gradientLayer.frame = bounds

但不幸的是,我不知道如何在@IBDesignable 中以编程方式将渐变层宽度设置为与原始按钮相同的大小class

你能帮我解决这个问题吗?提前致谢

覆盖 GradientButton 内的 layoutSubviews 并将 gradientLayer frame 更新为

override func layoutSubviews() {
    super.layoutSubviews()

    self.gradientLayer.frame = bounds
}