我的 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 中的任何按钮类
关于ios - 每次在按钮中完成点击时执行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59094789/