【问题标题】:Custom UIButton class for button touch event用于按钮触摸事件的自定义 UIButton 类
【发布时间】:2018-07-03 15:36:37
【问题描述】:

是否可以创建一个自定义 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)

     }
  }

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

有没有可能做这样的事情?

【问题讨论】:

  • @mr-tann :看看下面发布的答案,让我知道它是否有效

标签: ios swift uibutton uiviewanimation


【解决方案1】:

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

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 

    }
}

【讨论】:

    【解决方案2】:

    虽然我不喜欢子类化UIButton,但您希望使用子类化UIButton 为按钮实现的动画操作可以通过覆盖sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) 来实现

    根据 UIControl 类中的 cmets(UIButton 继承自 UIControl

    发送动作。第一个方法是为事件调用的,是一个 您可以观察或覆盖行为的点

    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)
        }
    }
    

    因此,只要点击按钮,您的动画就会被执行,然后IBAction 将被调用。希望这会有所帮助

    【讨论】:

    • 这也需要添加目标才能触发
    • @sh-khan : 问题不在于如何避免添加目标,而是在用户触摸按钮时调用动画而不实际显式触发每个动作/目标中的 buttonClicked 方法
    • 是的,但这也需要将按钮链接到一个虚拟的空 IBAction
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多