用于按钮触摸事件的自定义 UIButton 类 [英] Custom UIButton class for button touch event

查看:19
本文介绍了用于按钮触摸事件的自定义 UIButton 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个自定义 UIButton 类,其中包含每次用户触摸按钮时都会自动调用的触摸事件动画?

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)

     }
  }

所以我不想在 ViewController 中创建必须调用 button.buttonTouched() 的操作.每次我在所有 UIButton 中使用此类时,都会自动发生这种情况.

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?

推荐答案

像这样创建按钮的自定义类

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 

    }
}

这篇关于用于按钮触摸事件的自定义 UIButton 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆