[英]Custom UIButton class for button touch event
Is it possible to create a custom UIButton class with an touch event animation which gets automatically invoked everytime the user touches the button? 是否可以创建一个带有触摸事件动画的自定义UIButton类,每次用户触摸按钮时都会自动调用该动画?
import UIKit
class AnimatedButton: UIButton {
@objc private func buttonClicked(sender: UIButton) {
UIView.animate(withDuration: 0.5,
delay: 1.0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.2,
options: .curveEaseOut,
animations: {
//do animation
sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
},
completion: nil)
}
}
So I don't want to create an action in a ViewController in which button.buttonTouched() must be invoked. 所以我不想在其中必须调用button.buttonTouched()的ViewController中创建一个动作。 This should happen automatically everytime I use this class in all UIButton.
每当我在所有UIButton中使用此类时,这应该自动发生。
Is there any possibility to do something like that? 有可能做这样的事情吗?
Though subclassing UIButton
is not something that I would prefer, the animating action that you wanna achieve for your button with subclassing UIButton
can be achieved by overriding sendAction(_ action: Selector, to target: Any?, for event: UIEvent?)
虽然继承
UIButton
不是东西,我愿意,你想实现与子类按钮所处的动画动作UIButton
可以通过重载实现sendAction(_ action: Selector, to target: Any?, for event: UIEvent?)
As per comments in UIControl
class ( UIButton
inherits from UIControl
) 根据
UIControl
类中的注释( UIButton
继承自UIControl
)
send the action.
发送动作。 the first method is called for the event and is a point at which you can observe or override behavior
第一个方法被称为事件,它是您可以观察或覆盖行为的一点
class MyButton : UIButton {
override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
debugPrint("Am here")
//do all your animation stuff here
super.sendAction(action, to: target, for: event)
}
}
So whenever button is tapped your animation will be executed and then IBAction
will be invoked. 因此,每当点击按钮时,将执行动画,然后将调用
IBAction
。 Hope this helps 希望这可以帮助
Create the button's custom class like this 像这样创建按钮的自定义类
class CustomButton:UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
configeBtn()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configeBtn()
}
func configeBtn() {
self.addTarget(self, action: #selector(btnClicked(_:)), for: .touchUpInside)
}
@objc func btnClicked (_ sender:UIButton) {
// animate here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.