Skip to content

Instantly share code, notes, and snippets.

@fcanas
Last active January 16, 2018 01:56
Show Gist options
  • Save fcanas/77436ad3b61ed01ac991 to your computer and use it in GitHub Desktop.
Save fcanas/77436ad3b61ed01ac991 to your computer and use it in GitHub Desktop.
Button Spring Behavior
import UIKit
var SpringKey :Int = 0
class ButtonSpringBehavior: NSObject {
var scaleFactor :CGFloat = 1.3
init(button: UIButton) {
super.init()
button.addTarget(self, action: #selector(springOut(sender:)), for: UIControlEvents.touchDown)
button.addTarget(self, action: #selector(restore(sender:)), for: UIControlEvents.touchUpInside)
button.addTarget(self, action: #selector(restore(sender:)), for: UIControlEvents.touchDragExit)
objc_setAssociatedObject(button, &SpringKey, self, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
class func addToButton(button: UIButton) {
_ = ButtonSpringBehavior(button: button)
}
@objc private func springOut(sender: UIButton!) {
UIView.animate(withDuration: 0.3, delay: 0,
usingSpringWithDamping: 0.5, initialSpringVelocity: 0,
options: UIViewAnimationOptions.allowUserInteraction,
animations: { () -> Void in
sender.layer.transform = CATransform3DMakeScale(self.scaleFactor, self.scaleFactor, 1.0)
}, completion: nil)
}
@objc private func restore(sender: UIButton!) {
UIView.animate(withDuration: 0.3, delay: 0,
usingSpringWithDamping: 0.5, initialSpringVelocity: 0,
options: UIViewAnimationOptions.allowUserInteraction,
animations: { () -> Void in
sender.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0)
}, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment