我的Swift按钮中具有以下扩展名:
extension UIButton {
func backgroundChange() {
let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.duration = 0.3
colorAnimation.isAdditive = true
colorAnimation.fromValue = UIColor.black.cgColor
colorAnimation.toValue = self.layer.backgroundColor
colorAnimation.repeatCount = 1
colorAnimation.autoreverses = true
layer.add(colorAnimation, forKey: nil)
}
}
基本上基本上只是在按钮上触发“闪光”动画。问题是,每次我希望发生这种情况时,我都必须手动调用此方法。
我应该对此做些什么修改,以便每当您点击一个按钮时,类本身就会发生这种情况?或者,换句话说,如何覆盖所有UIButton通用的“ onClick”方法,以便在点击时它们都自动闪烁?
编辑:用户已将此问题标记为重复。但它不是。他们链接的问题根本无法回答我的问题。
我找到了正确的方法。这是要走的路:
override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent?){
backgroundChange()
super.touchesBegan(touches as! Set<UITouch>, with: with)
}
您需要创建一个类似的子类
class CustomButton: UIButton {
override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent?){
backgroundChange()
super.touchesBegan(touches as! Set<UITouch>, with: with)
}
func backgroundChange() {
let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.duration = 0.3
colorAnimation.isAdditive = true
colorAnimation.fromValue = UIColor.black.cgColor
colorAnimation.toValue = self.layer.backgroundColor
colorAnimation.repeatCount = 1
colorAnimation.autoreverses = true
layer.add(colorAnimation, forKey: nil)
}
}
然后将其分配给IB中的任何按钮类