Skip to content

Instantly share code, notes, and snippets.

@adamdahan
Forked from dfelber/BouncyButton.swift
Created May 8, 2022 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamdahan/e20f226595cb205610df9f05d2bbd10c to your computer and use it in GitHub Desktop.
Save adamdahan/e20f226595cb205610df9f05d2bbd10c to your computer and use it in GitHub Desktop.
Bouncy UIButton in swift. Becomes small when pressed and restores its size when released. Swift 3
//
// BouncyButton.swift
//
// Created by Domink Felber on 20.03.16.
// Copyright © 2016 Domink Felber. All rights reserved.
//
import Foundation
import UIKit
class BouncyButton: UIButton {
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let ret = super.beginTracking(touch, with: event)
if ret {
onTouchDown()
}
return ret
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
onTouchUp()
super.endTracking(touch, with: event)
}
override func cancelTracking(with event: UIEvent?) {
onTouchUp()
super.cancelTracking(with: event)
}
func onTouchDown() {
UIView.animate(withDuration: 0.3,
delay: 0.0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 2.0,
options: UIViewAnimationOptions.allowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}, completion: nil)
}
func onTouchUp() {
UIView.animate(withDuration: 1.2,
delay: 0.0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 3.0,
options: UIViewAnimationOptions.allowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment