Skip to content

Instantly share code, notes, and snippets.

@dfelber
Last active December 6, 2016 15:44
Show Gist options
  • Save dfelber/d2bef62af17a49171d62 to your computer and use it in GitHub Desktop.
Save dfelber/d2bef62af17a49171d62 to your computer and use it in GitHub Desktop.
Bouncy UIButton in swift. Becomes small when pressed and restores its size when released. Swift 2
//
// 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 beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let ret = super.beginTrackingWithTouch(touch, withEvent: event)
if ret {
onTouchDown()
}
return ret
}
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?)
{
onTouchUp()
return super.endTrackingWithTouch(touch, withEvent: event)
}
override func cancelTrackingWithEvent(event: UIEvent?)
{
onTouchUp()
return super.cancelTrackingWithEvent(event)
}
func onTouchDown()
{
UIView.animateWithDuration(1.2,
delay: 0.0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(0.6, 0.6)
}, completion: nil)
}
func onTouchUp()
{
UIView.animateWithDuration(1.2,
delay: 0.0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(1.0, 1.0)
}, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment