Skip to content

Instantly share code, notes, and snippets.

@dfelber
Last active May 8, 2022 05:38
Show Gist options
  • Save dfelber/9ba62085f7015ac3a89b3eb0cede640e to your computer and use it in GitHub Desktop.
Save dfelber/9ba62085f7015ac3a89b3eb0cede640e 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