Forked from mourad-brahim/UIView+Animations.swift
Last active
January 22, 2018 20:13
-
-
Save AD-Paladins/c16c8385d80316db5caeb892bee6a55f to your computer and use it in GitHub Desktop.
Shake animation with swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
shake2: for shaking just horizontally