Skip to content

Instantly share code, notes, and snippets.

@AD-Paladins
Forked from mourad-brahim/UIView+Animations.swift
Last active January 22, 2018 20:13
Show Gist options
  • Save AD-Paladins/c16c8385d80316db5caeb892bee6a55f to your computer and use it in GitHub Desktop.
Save AD-Paladins/c16c8385d80316db5caeb892bee6a55f to your computer and use it in GitHub Desktop.
Shake animation with swift
extension UIView {
func shake(duration: CFTimeInterval) {
let translation = CAKeyframeAnimation(keyPath: "transform.translation.x");
translation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
translation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0]
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0].map {
(let degrees: Double) -> Double in
let radians: Double = (M_PI * degrees) / 180.0
return radians
}
let shakeGroup: CAAnimationGroup = CAAnimationGroup()
shakeGroup.animations = [translation, rotation]
shakeGroup.duration = duration
self.layer.addAnimation(shakeGroup, forKey: "shakeIt")
}
func shake2() {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.07
animation.repeatCount = 5
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x:self.center.x - 10, y:self.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x:self.center.x + 10, y:self.center.y))
self.layer.add(animation, forKey: "position")
}
}
@AD-Paladins
Copy link
Author

shake2: for shaking just horizontally

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