I made a custom gradient Button, such that I can change the gradient color on different states:
class GradientButton: UIButton {
public var buttongradient: CAGradientLayer = CAGradientLayer()
override var isSelected: Bool {
didSet {
if isSelected {
buttongradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!].map { $0.cgColor }
} else {
buttongradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor }
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addthegradientLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addthegradientLayer()
}
override func layoutSubviews() {
super.layoutSubviews()
self.addthegradientLayer()
}
func addthegradientLayer() {
//the cells gradient colors
buttongradient.frame = self.bounds
buttongradient.cornerRadius = buttongradient.frame.height / 2
buttongradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor }
buttongradient.startPoint = CGPoint(x: 1.0, y: 0.0)
buttongradient.endPoint = CGPoint(x: 0.0, y: 1.0)
self.layer.insertSublayer(buttongradient, at: 0)
}
When I run this code, the button background is clear. No Gradient showing.
EDIT
As in the comments suggested:
buttongradient.frame = self.bounds
is the solution.
Follow up Problem
Now I realise, that the gradient does not change colors based on the isSelected state.