[英]Execute a method every time a tap is done in a button
I have the following extension in my Swift buttons :我的 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)
}
}
Which basically just triggers a "flash" animation in the button.这基本上只是触发按钮中的“闪光”动画。 The thing is, I have to manually call this method every time I want this to happen.
问题是,每次我希望发生这种情况时,我都必须手动调用此方法。
What should I modify on this so this happens for the class itself whenever you tap a button?我应该对此进行什么修改,以便每当您点击按钮时都会为类本身发生这种情况? Or, to put things differently, how can I override an "onClick" method common for all UIButtons so they all flash automatically when tapped?
或者,换一种说法,我如何覆盖所有 UIButton 通用的“onClick”方法,以便它们在点击时都自动闪烁?
EDIT: Users have flagged this question as a duplicate.编辑:用户已将此问题标记为重复。 But ITS NOT.
但它不是。 The question they have linked does not answer my question AT ALL.
他们链接的问题根本不能回答我的问题。
I found the right approach.我找到了正确的方法。 This is the way to go :
这是要走的路 :
override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent?){
backgroundChange()
super.touchesBegan(touches as! Set<UITouch>, with: with)
}
You need to create a subclass like您需要创建一个子类,例如
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)
}
}
then assign it to any button class in IB然后将其分配给 IB 中的任何按钮类
Much easier -容易多了——
@IBAction func keyPressed(_ sender: UIButton) {
//button Title is sound.wav filename
playSound(soundName: sender.currentTitle!)
//Reduces the sender's (the button that got pressed) opacity to half.
sender.alpha = 0.5
//the following Code should execute after 0.2 second delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//Bring's sender's opacity back up to fully opaque, thus completing the "blink" effect on press
sender.alpha = 1.0
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.