简体   繁体   中英

Applying Gradient to button doesn't reflect in swift

I have written the following code and don't know what I'm doing wrong the button is not reflecting the gradient

I also tried calling my function under 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)


    }
}

I want to apply gradient vertically to my button.

It's pretty simple, here you are

    @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]
    }

}

Just change class from UIButton to GradientButton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM