将渐变应用于按钮不会快速反映

时间:2019-07-30 10:38:10

标签: ios swift xcode uibutton

我编写了以下代码,不知道我在做什么错,按钮未反映渐变

我还尝试在awakefromNib下调用函数

class ButtonGradient: UIButton {

    var color1 = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
    var color2 = #colorLiteral(red: 0.521568656, green: 0.1098039225, blue: 0.05098039284, alpha: 1)

    var gradient = CAGradientLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        applyGradient()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        applyGradient()

    }


    func applyGradient() {

        gradient.frame = self.bounds
        gradient.colors = [color1,color2]
        gradient.startPoint = CGPoint.zero
        gradient.endPoint = CGPoint.init(x: 0.0, y: 0.5)
        gradient.locations = [0,1]
        self.layer.addSublayer(gradient)


    }
}

我想在按钮上垂直应用渐变。

1 个答案:

答案 0 :(得分:0)

这很简单,您在这里

    @IBDesignable class GradientButton: UIButton {

    @IBInspectable var topColor: UIColor = .white
    @IBInspectable var bottomColor: UIColor = .black

    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    override func layoutSubviews() {
        (layer as? CAGradientLayer)?.colors = [topColor.cgColor, bottomColor.cgColor]
    }

}

只需将类从UIButton更改为GradientButton