我制作了一个自定义渐变按钮,这样我就可以在不同的状态下更改渐变颜色:
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)
}
运行此代码时,按钮背景清晰。没有渐变显示。
修改
如同建议的评论:
buttongradient.frame = self.bounds
是解决方案。
跟进问题
现在我意识到,渐变不会根据isSelected状态改变颜色。
答案 0 :(得分:0)
存在多个问题:
.seek(0)
来更新图层框架。self.bounds
。layoutSubviews
,而不是isHighlighted
。isSelected
。buttongradient.colors
(见How to use hex colour values)。0x29a1e2