Swift UIButton 扩展动画覆盖

Swift UIButton Extension Animations Override

所以我有一个 UIButton Extension 允许我的应用程序中的所有按钮都有一个漂亮的微妙动画。但最近我想给几个按钮一个特殊的动画,但我不知道如何给这几个按钮一个特定的不同动画,而不是我为所有 UIButtons 普遍设置的动画。有没有办法 override 这个动画只针对几个特定的​​按钮?

通用按钮动画扩展代码:

extension UIButton {
   override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
   {
    self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: {
        self.transform = CGAffineTransform.identity
    }, completion: nil)
    super.touchesBegan(touches, with: event)
  }
}

我认为最好的办法是创建 UIButton 的子类,它们都做不同的事情,而不是创建 UIButton 的扩展。扩展应该添加新功能,而不是覆盖现有方法,例如 touchesBegan.

你应该删除你的分机并写一个SubtleAnimationButton:

class SubtleAnimationButton : UIButton {
   override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
   {
    self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: {
        self.transform = CGAffineTransform.identity
    }, completion: nil)
    super.touchesBegan(touches, with: event)
  }
}

并改用 SubtleAnimationButton

对于那些您想要覆盖行为的按钮,您应该使用不同的子类。我称之为 SpecialButton.

class SpecialButton : UIButton {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // something else
    }
}