【问题标题】:How to add animation to custom button and call whenever button is tapped? [duplicate]如何为自定义按钮添加动画并在点击按钮时调用? [复制]
【发布时间】:2019-02-06 11:31:50
【问题描述】:

我创建了一个自定义按钮类,它是 UIButton 的子类, 并编写一个 UIButton 扩展。

这是我的扩展:

extension UIButton {

    func setButtonCurvy() {
        self.layer.cornerRadius = self.frame.size.height/2
    }

    //This function should be run when button tapped
    func buttonTapped(_ completion: @escaping () -> Void) {

        let anim = CASpringAnimation(keyPath: "transform.scale")
        anim.fromValue = 0.9
        anim.toValue = 1.1
        anim.timingFunction = CAMediaTimingFunction(name: .easeIn)
        anim.autoreverses = true
        anim.repeatCount = 0
        anim.duration = 1

        self.layer.add(anim, forKey: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
            completion()
        }
    }
}

我的课是:

class MyButton: UIButton {
    //Customize buttons...
    override func awakeFromNib() {

        self.setButtonCurvy()
        self.backgroundColor = UIColor.mainButtonColor()
        switch self.tag {
        case 1:
            self.titleLabel?.font = UIFont(name: "Mostley Script", size: 23)
            break
        case 2:
            self.titleLabel?.font = UIFont(name: "Mostley Script", size: 20)
            break
        default:
            self.titleLabel?.font = UIFont(name: "Mostley Script", size: 38)
            break
        }
    }

}

所以这是我的问题,我在文档中找不到,并提出了问题。也许我只是错过了一些明显的东西。 有什么方法可以在点击我的按钮时调用 buttonHitted() 函数?

【问题讨论】:

  • 通过 UIButton 的实例从按钮的操作方法中调用 buttonTapped 方法。
  • 您可以在 UIButton 的 touchupinside 事件上添加操作。每当您按下按钮时都会调用它
  • 您在哪里以及如何使用MyButton ?请分享一些代码。
  • 你好@Mahak Mittal,@Mayur Karmur 当然我知道我可以在我的动作方法中调用这个函数。但是有大量的类和按钮,我不想重复自己。

标签: ios swift xcode uikit


【解决方案1】:

嗨@Said Alır @AtulParmar 的回答很好,但如果您只需要在特定类型的事件(例如(touchUpInside))的情况下制作动画,请尝试以下解决方案。

import UIKit
class MyButton: UIButton {

    override func awakeFromNib() {
        super.awakeFromNib()

        self.addTarget(self, action: #selector(MyButton.touchUpInside), for: .touchUpInside)
    }
    @objc func touchUpInside() {
        //Perform you animations here
    }
}

【讨论】:

  • 您好,谢谢您的回答,但正如我解释的那样,我有大量的类和大量的按钮,我想为它们添加动画。这就是@AtulParmar 的解决方案很多的原因对我来说更好..谢谢
  • 我猜你弄错了,方法在 UIButton 继承类中,这意味着你必须在你的自定义按钮类中提供一个实现,并在整个项目中的任何地方重复使用这个按钮来实现动画。甚至您可以从 UIControl 类扩展并可以在所有其他控件中实现动画。例如,从 UIDatePicker、UIPageControl、UISegmentedControl、UISlider、UIStepper、UISwitch 继承的类只在一个地方实现一次方法。 ;-)
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多