【问题标题】:Swift UIButton Extension Animations OverrideSwift UIButton 扩展动画覆盖
【发布时间】:2019-08-10 20:00:57
【问题描述】:

所以我有一个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)
  }
}

【问题讨论】:

    标签: ios swift uibutton core-animation swift-extensions


    【解决方案1】:

    我认为最好的做法是创建 UIButtons 的子类,它们都做不同的事情,而不是创建 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
        }
    }
    

    【讨论】:

    • 好的!但是我怎么称呼它呢?我必须在每个按钮上调用这个动画吗?像有没有办法让它默认为'SubtleAnimationButton'?我不想听起来很懒惰,我只是在应用程序中有很多按钮,当然大多数人都这样做。
    • 只需将每个UIButton 替换为SubtleAnimationButton。这可以通过查找和替换功能轻松完成。 @MattTheDev
    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多