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

时间:2019-08-05 04:53:48

标签: ios swift uibutton ibdesignable

我是iOS开发的新手,我想使用此可设计的类制作渐变圆角按钮

@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()
        }
    }
}

但这是结果:

enter image description here

您会看到渐变层按钮的宽度不正确。

这是我使用的约束布局:

enter image description here

我希望该渐变层具有与原始按钮相同的宽度,我怀疑问题出在这行

gradientLayer.frame = bounds

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

能帮我解决这个问题吗?预先感谢

1 个答案:

答案 0 :(得分:1)

'title' => $this->when(!is_null($this->title), $this->title), 'subtitle' => $this->when(!is_null($this->subtitle), $this->subtitle) 内覆盖layoutSubviews,并将GradientButton gradientLayer更新为

frame