UIButton subclassification and sensory event redefinition - not working

I need a large-scale spring animation for all my buttons in a project. Thus, I subclassed UIButton and canceled touch event functions.

import UIKit

class UIAnimatedButton: UIButton {

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    UIView.animateWithDuration(0.1, animations: { () -> Void in
        self.transform = CGAffineTransformMakeScale(0.8, 0.8)

    })
    super.touchesBegan(touches, withEvent: event)

}

override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {


    UIView.animateWithDuration(0.5,
        delay: 0,
        usingSpringWithDamping: 0.2,
        initialSpringVelocity: 6.0,
        options: UIViewAnimationOptions.AllowUserInteraction,
        animations: { () -> Void in
            self.transform = CGAffineTransformIdentity
    }) { (Bool) -> Void in
        super.touchesCancelled(touches, withEvent: event)
    }

}


override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

    UIView.animateWithDuration(0.5,
        delay: 0,
        usingSpringWithDamping: 0.2,
        initialSpringVelocity: 6.0,
        options: UIViewAnimationOptions.AllowUserInteraction,
        animations: { () -> Void in
            self.transform = CGAffineTransformIdentity
        }) { (Bool) -> Void in
            super.touchesEnded(touches, withEvent: event)
    }
  }
} 

this works great in quick press, but when I touch the button for a long time (1-2 seconds), I don’t get a touch inside the action event. when i switch it back to regular UIButton everything works fine.

Any ideas why this is happening?

+5
source share
2 answers

Instead of calling super in the method completion block touchesCancelled, touchesEndedI called self.sendActionsForControlEvents(UIControlEvents.TouchUpInside)there.

+6
source

, , super.touchesEnded(touches, with: event)

(Swift 5)

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    UIView.animate(withDuration: 0.5,
        delay: 0,
        usingSpringWithDamping: 0.2,
        initialSpringVelocity: 6.0,
        options: UIView.AnimationOptions.allowUserInteraction,
        animations: { () -> Void in
            self.transform = CGAffineTransform.identity
        }) { (Bool) -> Void in
    }
    super.touchesEnded(touches, with: event)
}
0

All Articles