Search code examples
iosswiftuibuttoncore-animationswift-extensions

Swift UIButton Extension Animations Override


So I have a UIButton Extension that allows all the buttons in my app to have a nice subtle animation. But recently I have thought of giving a few buttons a special animation but I am not sure how to give those few buttons a specific different animation other than the one that I have set universally for all the UIButtons. Is there a way to override this animation for just a few specific buttons?

Code for the extension of the button animation universally:

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

Solution

  • I think the best thing to do here is to create subclasses of UIButtons that all do different things, instead of creating extensions of UIButton. Extensions are supposed to add new functionality, not override existing methods, like touchesBegan.

    You should delete your extension and write a 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)
      }
    }
    

    And use SubtleAnimationButton instead.

    For those buttons where you want to override the behaviour, you should use a different subclass. I'll call this SpecialButton.

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