Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created January 12, 2022 17:25
Show Gist options
  • Save sindresorhus/06dbd418aa3e62b489a1fe3a1c6decb5 to your computer and use it in GitHub Desktop.
Save sindresorhus/06dbd418aa3e62b489a1fe3a1c6decb5 to your computer and use it in GitHub Desktop.

Revisions

  1. sindresorhus created this gist Jan 12, 2022.
    33 changes: 33 additions & 0 deletions NSView+shake.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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)
    }
    }