Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created January 12, 2022 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindresorhus/06dbd418aa3e62b489a1fe3a1c6decb5 to your computer and use it in GitHub Desktop.
Save sindresorhus/06dbd418aa3e62b489a1fe3a1c6decb5 to your computer and use it in GitHub Desktop.
Shake a NSView
extension NSView {
/**
Shake the view.
- Note: It will do nothing if the user has enabled the “Reduce motion” accessibility preference.
*/
func shake(
duration: TimeInterval = 0.3,
direction: NSUserInterfaceLayoutOrientation,
moveAmount: Double = 5
) {
wantsLayer = true
guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else {
return
}
let translation = direction == .horizontal ? "x" : "y"
let animation = CAKeyframeAnimation(keyPath: "transform.translation.\(translation)")
animation.timingFunction = .easeInOut
animation.duration = duration
animation.values = [
-moveAmount,
moveAmount,
-(moveAmount / 2),
moveAmount / 2,
0
]
layer?.add(animation, forKey: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment