Created
January 12, 2022 17:25
-
-
Save sindresorhus/06dbd418aa3e62b489a1fe3a1c6decb5 to your computer and use it in GitHub Desktop.
Shake a NSView
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 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