Skip to content

Instantly share code, notes, and snippets.

@SAllen0400
Created March 15, 2017 00:04
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save SAllen0400/a09754049fcdcc00695291b3a011fbbd to your computer and use it in GitHub Desktop.
Save SAllen0400/a09754049fcdcc00695291b3a011fbbd to your computer and use it in GitHub Desktop.
Core Animation on UIButton Example
// Swift 3
extension UIButton {
func pulsate() {
let pulse = CASpringAnimation(keyPath: "transform.scale")
pulse.duration = 0.6
pulse.fromValue = 0.95
pulse.toValue = 1.0
pulse.autoreverses = true
pulse.repeatCount = 2
pulse.initialVelocity = 0.5
pulse.damping = 1.0
layer.add(pulse, forKey: "pulse")
}
func flash() {
let flash = CABasicAnimation(keyPath: "opacity")
flash.duration = 0.5
flash.fromValue = 1
flash.toValue = 0.1
flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
flash.autoreverses = true
flash.repeatCount = 3
layer.add(flash, forKey: nil)
}
func shake() {
let shake = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let fromPoint = CGPoint(x: center.x - 5, y: center.y)
let fromValue = NSValue(cgPoint: fromPoint)
let toPoint = CGPoint(x: center.x + 5, y: center.y)
let toValue = NSValue(cgPoint: toPoint)
shake.fromValue = fromValue
shake.toValue = toValue
layer.add(shake, forKey: "position")
}
}
// Example of using the extension on button press
@IBAction func pulseButtonPressed(_ sender: UIButton) {
sender.pulsate()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
sender.flash()
}
@IBAction func shakeButtonPressed(_ sender: UIButton) {
sender.shake()
}
@zabeehqayumi
Copy link

Hi Sean,
Thank you very much for the tutorial, i loved the way you did but i have one issue. you did this in swift 3 but i am working in swift 4. Now, in the NSValue part, do i need to add NS or not?
thanks.

@ajRiverav
Copy link

swift 4 update:

flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment