Custom UIButton class for button touch event

匆匆过客 提交于 2019-12-23 04:55:31

问题


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?


回答1:


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




回答2:


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 

    }
}


来源:https://stackoverflow.com/questions/51158390/custom-uibutton-class-for-button-touch-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!