简体   繁体   中英

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?

 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. This should happen automatically everytime I use this class in all 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?)

As per comments in UIControl class ( UIButton inherits from 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. 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 

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM