Last active
June 11, 2024 14:07
-
-
Save mourad-brahim/cf0bfe9bec5f33a6ea66 to your computer and use it in GitHub Desktop.
Shake animation with swift
This file contains 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") | |
} | |
} |
@shawnwall, @aayusharyan and @rmnblm, many thanks for your updates
Is there sample code that show us how to use it with Images or TextFields etc ?
updated for swift 5.1
extension UIView {
func shake(duration: CFTimeInterval) {
let shakeValues = [-5, 5, -5, 5, -3, 3, -2, 2, 0]
let translation = CAKeyframeAnimation(keyPath: "transform.translation.x");
translation.timingFunction = CAMediaTimingFunction(name: .linear)
translation.values = shakeValues
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotation.values = shakeValues.map { (Int(Double.pi) * $0) / 180 }
let shakeGroup = CAAnimationGroup()
shakeGroup.animations = [translation, rotation]
shakeGroup.duration = 1.0
layer.add(shakeGroup, forKey: "shakeIt")
}
}
Is there sample code that show us how to use it with Images or TextFields etc ?
myTextField..shake(duration: 1.0)
updated for swift 5.1
extension UIView { func shake(duration: CFTimeInterval) { let shakeValues = [-5, 5, -5, 5, -3, 3, -2, 2, 0] let translation = CAKeyframeAnimation(keyPath: "transform.translation.x"); translation.timingFunction = CAMediaTimingFunction(name: .linear) translation.values = shakeValues let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotation.values = shakeValues.map { (Int(Double.pi) * $0) / 180 } let shakeGroup = CAAnimationGroup() shakeGroup.animations = [translation, rotation] shakeGroup.duration = 1.0 layer.add(shakeGroup, forKey: "shakeIt") } }
Many thanks for the update. You maybe forgot to use the animation duration parameter:
shakeGroup.duration = duration
insteed of
shakeGroup.duration = 1.0
Hocam kolay gelsin bu windowsta calisan uiview de nasil görüntülenir acaba
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 5.0